即使在使用extern和#ifdef时,也已在.obj中定义

问题描述

我有三个这样的文件:

head.h

#ifndef HEAD_
#define HEAD_

extern int f();

#endif

mycpp.cpp

#include "head.h"

int f() {
    return 5;
}

myMain.cpp

#include <iostream>
#include "head.h"
#include "mycpp.cpp"

int main()
{
    std::cout << f() << std::endl;
    system("Pause");
    return 0;
}

运行此代码会产生链接错误:

在mycpp.obj中已经定义的LNK2005“ int __cdecl f(void)”(?f @@ YAHXZ)

如果我在inline的函数f中添加mycpp.cpp,错误就会消失。

我的问题是如何在不使用inline函数的情况下摆脱此错误?

P.S。这是一项作业,我只能修改mycpp.cpp文件。因此#include "mycpp.cpp"必须在那里。

我知道包含cpp文件是一个坏主意,但是我不能更改myMain文件。它是通过这种方式给出的。而且我不应该使用inline

解决方法

一般规则是:从不 files = {'A.txt':12,'B.txt':34,'C.txt':56,'D.txt':78} filesFrame = pd.DataFrame(files.items(),columns=['filename','size']) print(filesFrame) filename size 0 A.txt 12 1 B.txt 34 2 C.txt 56 3 D.txt 78 一个#include文件。仅应包含头文件。

此外,函数声明中的.cpp在这里是多余的。在变量声明上,extern将语句标记为声明而不是定义。但是,在函数声明中这不是必需的,并且该函数始终具有外部链接。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...