What is an undefined reference/unresolved external symbol error and how do I fix it?
昨天碰到的bug,稍微查了一下有了一些理解,其实对程序的前世今生还不明白,C++的scope这个事情,对于我来说依然是个迷
注意第一个回答,那个回答的是标题的问题
其中他所说的程序运行的第九个步骤
All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment.
解释一下。C++在编译的时候,会认为你所声明的那些变量都是存在的,都可以找得到。在link阶段编译器才会去找该符号是从哪里找到其定义。如果没有在并非你所在scope内定义的变量没有声明就在该文件内使用了,就会出现这种错误。
1 struct X 2 { 3 virtual void foo(); 4 }; 5 struct Y : X 6 { 7 void foo() {} 8 }; 9 struct A 10 { 11 virtual ~A() = 0; 12 }; 13 struct B: A 14 { 15 virtual ~B(){} 16 }; 17 extern int x; 18 void foo(); 19 int main() 20 { 21 x = 0; 22 foo(); 23 Y y; 24 B b; 25 }
如上面的代码,其实会出现不少错误...
这里贴出VS的编译错误
1>test2.obj : error LNK2001: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ) 1>test2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA) 1>test2.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ) 1>test2.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall X::foo(void)" (?foo@X@@UAEXXZ) 1>...\test2.exe : fatal error LNK1120: 4 unresolved externals
其中x被声明为extern,但是外部没有这个东西的定义
foo被声明了,但是找不到它的定义
后面那个我以为会出现虚函数表错误,但结果也是没有找到符号链接
程序员修炼之道那本书需要看掉,自己对程序的运行还是很迷茫的感觉,对C++依然是很苦手。

浙公网安备 33010602011771号