使用编译命令:'g++ polymorphism_t.cpp -lpthread' 出现如下报错:

/usr/bin/ld: /tmp/ccwHN6qN.o: warning: relocation against `_ZTV6Thread' in read-only section `.text._ZN6ThreadC2Ev[_ZN6ThreadC5Ev]'
/usr/bin/ld: /tmp/ccwHN6qN.o: in function `Thread::Thread()':
polymorphism_t.cpp:(.text._ZN6ThreadC2Ev[_ZN6ThreadC5Ev]+0xf): undefined reference to `vtable for Thread'
/usr/bin/ld: /tmp/ccwHN6qN.o:(.data.rel.ro._ZTI7Counter[_ZTI7Counter]+0x10): undefined reference to `typeinfo for Thread'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status

这个报错是因为没有找到Thread类的虚函数表(vtable)和Thread类的typeinfo信息。解决方法是在Thread类中声明一个虚函数(可以是一个空函数),这样就会自动生成虚函数表和typeinfo信息。

例如,在Thread类中添加一个空的虚函数:

class Thread {
public:
    virtual ~Thread() {}
    virtual void dummy() {}
};

然后重新编译即可:

g++ polymorphism_t.cpp -lpthread
C++ 编译错误:undefined reference to `vtable for Thread' 和 `typeinfo for Thread' 解决方法

原文地址: https://www.cveoy.top/t/topic/f1XB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录