C++编译报undefined reference to类成员函数错误该如何解决?
错误原因
undefined reference to 'N::my_class::do_something()'是典型的链接阶段错误,常见触发原因有两类:
- 函数实现所属的命名空间不匹配:你在
my_class.cpp中用using namespace N只是引入了N命名空间的名字查找规则,不会自动将后续定义的函数归属到N命名空间下。如果要定义N::my_class的成员函数,要么显式给类名加命名空间前缀,要么将函数实现包裹在N命名空间块中,否则链接器无法将头文件中声明的N::my_class::do_something和你实现的函数关联起来。 - 编译时未包含全部源文件:如果你只单独编译了
my_program.cpp,没有将my_class.cpp加入编译队列,链接器自然找不到do_something的实现代码。
解决方法
命名空间不匹配的修复方案
二选一即可:
- 方案1:将函数实现包裹在命名空间块中
修改my_class.cpp代码为:
#include "my_class.h" // header in local directory #include <iostream> // header in standard library using namespace std; namespace N { void my_class::do_something() { cout << "Doing something!" << endl; } }
- 方案2:显式指定函数的命名空间前缀
#include "my_class.h" // header in local directory #include <iostream> // header in standard library using namespace std; void N::my_class::do_something() { cout << "Doing something!" << endl; }
编译命令错误的修复方案
编译时需要将所有涉及的源文件一起传入编译器,以GCC为例,正确的编译命令为:
g++ my_program.cpp my_class.cpp -o my_program
如果使用Visual Studio等IDE,需要将my_class.cpp加入到当前项目的源文件列表中再编译运行。
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

