我只是遇到了以下错误:

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

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


当前回答

在我的例子中,它是一个接口类中的虚函数,没有定义为纯虚函数。

class IInterface
{
public:
  virtual void Foo() = 0;
}

我忘记了= 0位。

其他回答

一个可能的原因是声明了虚函数而没有定义它。

当你声明它而没有在同一个编译单元中定义它时,你就表明它在其他地方定义了——这意味着链接器阶段将尝试在其他编译单元(或库)中找到它。

定义虚函数的一个例子是:

virtual void fn() { /* insert code here */ }

在本例中,您将定义附加到声明中,这意味着链接器稍后不需要解析它。

这条线

virtual void fn();

声明fn()而不定义它,这将导致您所要求的错误消息。

它与代码非常相似:

extern int i;
int *pi = &i;

它声明整数I在另一个编译单元中声明,必须在链接时解析(否则PI不能设置为它的地址)。

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

virtual void foo();

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

virtual void foo() {}

或声明为纯虚拟的:

virtual void foo() = 0;

检查你的依赖是在没有-f-nortti的情况下编译的。

对于某些项目,你必须显式地设置它,比如在RocksDB中:

USE_RTTI=1 make shared_lib -j4

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.

我刚才有很多这样的错误。我将一个只包含头文件的类拆分为一个头文件和一个cpp文件。但是,我没有更新我的构建系统,所以cpp文件没有被编译。除了在头文件中声明但未实现的函数的未定义引用之外,我得到了很多此类typeinfo错误。

解决方案是重新运行构建系统来编译和链接新的cpp文件。