我只是遇到了以下错误:
(.gnu.linkonce。[内容]):定义 引用[方法][对象] 文件:(.gnu.linkonce。[内容]): 对' typeinfo for '的未定义引用 (名称)的
为什么可能会得到这些“未定义的引用typeinfo”链接错误之一? 有人能解释一下幕后发生了什么吗?
我只是遇到了以下错误:
(.gnu.linkonce。[内容]):定义 引用[方法][对象] 文件:(.gnu.linkonce。[内容]): 对' typeinfo for '的未定义引用 (名称)的
为什么可能会得到这些“未定义的引用typeinfo”链接错误之一? 有人能解释一下幕后发生了什么吗?
当前回答
当声明的(非纯)虚函数缺少主体时,就会发生这种情况。在你的类定义中,如下所示:
virtual void foo();
应该定义(内联或链接源文件中):
virtual void foo() {}
或声明为纯虚拟的:
virtual void foo() = 0;
其他回答
当声明的(非纯)虚函数缺少主体时,就会发生这种情况。在你的类定义中,如下所示:
virtual void foo();
应该定义(内联或链接源文件中):
virtual void foo() {}
或声明为纯虚拟的:
virtual void foo() = 0;
一个可能的原因是声明了虚函数而没有定义它。
当你声明它而没有在同一个编译单元中定义它时,你就表明它在其他地方定义了——这意味着链接器阶段将尝试在其他编译单元(或库)中找到它。
定义虚函数的一个例子是:
virtual void fn() { /* insert code here */ }
在本例中,您将定义附加到声明中,这意味着链接器稍后不需要解析它。
这条线
virtual void fn();
声明fn()而不定义它,这将导致您所要求的错误消息。
它与代码非常相似:
extern int i;
int *pi = &i;
它声明整数I在另一个编译单元中声明,必须在链接时解析(否则PI不能设置为它的地址)。
前面的答案是正确的,但是这个错误也可能是由于试图对没有虚函数的类的对象使用typeid而导致的。c++ RTTI需要虚表,因此希望对其执行类型标识的类至少需要一个虚函数。
如果希望类型信息作用于一个实际上不需要任何虚函数的类,可以将析构函数设为虚函数。
I encounter an situation that is rare, but this may help other friends in similar situation. I have to work on an older system with gcc 4.4.7. I have to compile code with c++11 or above support, so I build the latest version of gcc 5.3.0. When building my code and linking to the dependencies if the dependency is build with older compiler, then I got 'undefined reference to' error even though I clearly defined the linking path with -L/path/to/lib -llibname. Some packages such as boost and projects build with cmake usually has a tendency to use the older compiler, and they usually cause such problems. You have to go a long way to make sure they use the newer compiler.
引用gcc手册:
对于多态类(具有虚函数的类),type_info对象与虚表[…对于所有其他类型,我们在使用type_info对象时写出type_info对象:当将' typeid'应用到表达式、抛出对象或在catch子句或异常规范中引用类型时。
在同一页稍早的地方
如果类声明了任何非内联、非纯虚函数,则选择第一个虚函数作为类的“key方法”,虚表只在定义key方法的转换单元中发出。
因此,当“key方法”缺少它的定义时,就会发生这个错误,正如前面提到的其他答案。