我只是遇到了以下错误:

(.gnu.linkonce。[内容]):定义 引用[方法][对象] 文件:(.gnu.linkonce。[内容]): 对' typeinfo for '的未定义引用 (名称)的

为什么可能会得到这些“未定义的引用typeinfo”链接错误之一? 有人能解释一下幕后发生了什么吗?


当前回答

处理RTTI和非RTTI库的代码的可能解决方案:

a)使用-frtti或-fno-rtti重新编译所有内容 b)如果a)对你来说不可能,试试下面的方法:

假设libfoo是在没有RTTI的情况下构建的。您的代码使用libfoo并使用RTTI编译。如果你在libfoo中使用一个有虚拟对象的类(Foo),你很可能会遇到一个链接时错误:Foo类缺少typeinfo。

定义另一个类(例如FooAdapter),它没有虚值,并且会将调用转发给你使用的Foo。

在一个不使用RTTI且仅依赖于libfoo符号的小型静态库中编译FooAdapter。为它提供一个头文件,并在代码中使用它(使用RTTI)。因为FooAdapter没有虚函数,它不会有任何类型信息,你将能够链接你的二进制文件。如果您使用许多来自libfoo的不同类,这个解决方案可能不方便,但这是一个开始。

其他回答

如果你要将一个。so链接到另一个。so,还有一种可能性是在gcc或g++中使用"-fvisibility=hidden"进行编译。如果两个.so文件都是用"-fvisibility=hidden"构建的,并且key方法不相同。so作为另一个虚函数的实现,后者将看不到前者的虚表或typeinfo。对于链接器来说,这看起来像一个未实现的虚函数(就像paxdiablo和cdleary的答案一样)。

在这种情况下,必须为基类的可见性做出例外

__attribute__ ((visibility("default")))

在类声明中。例如,

class __attribute__ ((visibility("default"))) boom{
    virtual void stick();
}

当然,另一个解决方案是不使用"-fvisibility=hidden "。这使得编译器和链接器的事情变得复杂,可能会损害代码的性能。

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.

在我的情况下,这纯粹是一个库依赖问题,即使我有dynamic_cast调用。在makefile中添加了足够的依赖后,这个问题就消失了。

当声明的(非纯)虚函数缺少主体时,就会发生这种情况。在你的类定义中,如下所示:

virtual void foo();

应该定义(内联或链接源文件中):

virtual void foo() {}

或声明为纯虚拟的:

virtual void foo() = 0;

当混合使用-fno-rtti和-frtti代码时也会发生这种情况。然后,您需要确保在-frtti代码中访问type_info的任何类都使用-frtti编译了它们的key方法。这种访问可以发生在创建类的对象时,使用dynamic_cast等。

(来源)