【问题标题】:Already defined in .obj even when using extern and #ifdef即使使用 extern 和 #ifdef 也已在 .obj 中定义
【发布时间】:2020-10-12 18:26:20
【问题描述】:

我有三个这样的文件:

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;
}

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

LNK2005 "int __cdecl f(void)" (?f@@YAHXZ) 已在 mycpp.obj 中定义

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

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

附:这是一个作业,我只能修改mycpp.cpp 文件。所以#include "mycpp.cpp" 必须在那里。

我知道包含cpp 文件是个坏主意,但我无法更改myMain 文件。它是这样给出的。而且我不应该使用inline。

【问题讨论】:

  • already defined in io.obj - 看起来您在某些 io.cpp 文件中定义了 int f(),但您在问题中没有提及。
  • 致您的 P.S.,不,它没有。您可能只是应该在 cpp 文件中实现该功能。
  • @marcinj 我修复了那部分。没有其他文件。那应该是mycpp 文件。
  • @sweenish 我的意思是在作业中他们要求不要更改 myMain 或 head 文件。
  • @HadiGhahremanNezhad 你说你不能删除:#include "mycpp.cpp" ?然后也许把它放在一个命名空间中?像命名空间 RemoveThis { #include "mycpp.cpp" }。或者更确切地说 if-def it out :-)

标签: c++ linker-errors inline extern


【解决方案1】:

一般规则是:从不 #include .cpp 文件。只应包含头文件。

此外,函数声明中的extern 在这里是多余的。在变量声明中,extern 将语句标记为声明而不是定义。但在函数声明中,这不是必需的,而且函数无论如何都有外部链接。

【讨论】:

  • 我希望作业不会以必须包含 cpp 的方式编写。更有可能的情况是假设学生误解了要求,就像抨击老师一样有趣。
  • @sweenish 当然可以,但根据引用的部分,OP 非常明确地表明 main.cpp 文件是按原样提供的。
  • 我想我们可以继续讨论我们的假设,或者让 OP 澄清一下。我和你的阅读方式不同。可能只是我作为一名教师,但我希望那些无能的人不会在开设课程。
  • @sweenish 好的,我明白你的意思了。
  • @KonradRudolph head 和 myMain 文件已经给出。我没有在那里添加extern。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 2014-11-02
  • 2015-07-27
  • 2023-02-14
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多