提问人:xgreenmanx 提问时间:4/6/2021 最后编辑:double-beepxgreenmanx 更新时间:7/21/2021 访问量:945
在 C++ 的标头中使用命名空间时,未定义对链接器错误的引用 [duplicate]
Undefined reference to linker error when using namespaces in headers in c++ [duplicate]
问:
我已经阅读了所有类似的“未定义引用”线程,我可以找到但找不到解决方案。大多数其他线程还涉及我不打算为此使用的类。如果我在标头中定义函数而不是使用外部 .cc 文件,则程序编译正常执行。我觉得我在这里错过了一些简单的东西。
这是我能做的最简单的测试,它重现了我遇到的问题。
编译器: g++ (Debian 8.3.0-6) 8.3.0
hntest.h
namespace hntest
{
void pewpew();
}
hntest.cc
#include <iostream>
#include "hntest.h"
namespace hntest
{
void pewpew()
{
std::cout << "pew pew pew!!!" << std::endl;
}
}
hntestmain.cc
#include "hntest.h"
int main(int argc, char* argv[])
{
hntest::pewpew();
}
我正在尝试编译:
g++ -lstdc++ hntestmain.cc -o hntestmain
我收到以下链接器错误:
hntestmain.cc:(.text+0x10): undefined reference to `hntest::pewpew()'
collect2: error: ld returned 1 exit status
我尝试阅读了几个流行的 C++ 库的代码以及我自己的一些较旧的 C(不是 ++)代码和 makefile,但无法找到我的错误。诚然,我既是业余爱好者,又有点生疏。
我错过了什么?
答:
2赞
Fantastic Mr Fox
4/6/2021
#1
您实际上并没有编译定义为 的文件。cpp
pewpew
尝试:
g++ -lstdc++ hntestmain.cc hntest.cc -o hntestmain
编译器需要了解所有源文件。头文件在预处理期间处理,并且知道在同一文件夹中查找。你可以想象,如果你有更多的文件,比如 10、100 或 10000,这将变得不可能使用命令行进行管理。这就是为什么人们创建了像 和 这样的构建系统的原因。make
cmake
bazel
有关更多详细信息,请参阅此处的答案,该答案特定于您的链接器错误情况。
评论
0赞
xgreenmanx
4/6/2021
啊......我的菜鸟错误。完全忘记了我可以将定义文件与 main.cc 一起传递给编译器。我只在一个项目中使用了 make,这是我遵循的一个非常广泛的教程。我非常感谢您的回应和解释。
评论
hntest.cc