GCC 的未定义引用/多重定义错误

Undefined reference / multiple definition errors with GCC

我是 C++ 的新手。我在使用 g++ 构建一个简单的 multi-file 项目时遇到了问题。这是我的文件:

something.h

class Something
{
public:
    void do_something() const;
} thing;

something.cpp

#include <iostream>
#include "something.h"

void Something::do_something() const
{
    std::cout << "Hello!" << std::endl;
}

main.cpp

#include "something.h"

int main()
{
    thing.do_something();
}

这是我尝试过的:

任何人都可以解释如何编译 multi-file 项目,以及为什么我的方法不起作用?我现在很困惑,因为上面是 Stack Overflow 上大多数 C++ 示例的样子。


旁注:

g++ main.cpp gives an error that do_something is an undefined reference, which makes sense because the compiler has no idea something.cpp [...]

...其中包含定义的成员函数do_something存在。所以你引用了一个未定义的函数。

g++ -c main.cpp something.cpp: no errors! [...]

...因为您只是在编译文件,而不是link将它们放在一起。

当你 link 他们在一起时,你会得到

[...] 'multiple definitions' of thing [...]

这正是您正在做的事情:

class Something {
  // content
} thing;

相同
class Something {
 // content
};

Something thing;

并且由于 #include "something.h" 通过有效地将包含文件的内容直接复制到包含文件中来工作,因此您最终得到 2 个文件,其中一行

Something thing;

在他们每个人身上。这就是 linker(从编译器前端调用)告诉你的:全局变量 thing.

有多个定义

要解决此问题:不要将全局变量的定义放入 header 文件中,仅声明:

extern Something thing;

然后在单个源文件中添加定义:

Something thing;

或者,更好的是,尽量避免使用全局变量。


还有一件事:如果您还没有这样做,请为您的 header 使用 include guards。

确保您已将所有文件添加到项目中。 就像如果您使用 IDE 例如,DEV C++,您必须将每个 .cpp 或 .h 文件添加到项目中。