undefined symbols “typeinfo” for XXX calss

问题描述

在使用虚基类的时候,编译遇到了如下错误:

Undefined symbols for architecture x86_64:
  "typeinfo for HandlerBase", referenced from:
      typeinfo for DNSResolveHandler in test-dns-b857ca.o
      typeinfo for DNSResolver in asyncdns-061190.o
  "vtable for HandlerBase", referenced from:
      HandlerBase::HandlerBase() in test-dns-b857ca.o
      HandlerBase::HandlerBase() in asyncdns-061190.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

对应的代码为:

class HandlerBase{
    public:
        virtual void handleEvent(int socketfd, UCHAR event) = 0;
        virtual void handlePeriodic(void) = 0;
        // this virtual function is used in TCPRelay class
        virtual void handleDNSResolved(std::string hostname, std::string ip, \
                int error);
};

解决方案

应该在基类中定义虚函数(不能仅仅声明)或者将虚函数声明成纯虚函数。因此,可消除编译错误的方式有两种。

其一,定义虚函数

class HandlerBase{
    public:
        virtual void handleEvent(int socketfd, UCHAR event) = 0;
        virtual void handlePeriodic(void) = 0;
        // this virtual function is used in TCPRelay class
        virtual void handleDNSResolved(std::string hostname, std::string ip, \
                int error) {};
};

其二,声明虚函数喂纯虚函数

class HandlerBase{
    public:
        virtual void handleEvent(int socketfd, UCHAR event) = 0;
        virtual void handlePeriodic(void) = 0;
        // this virtual function is used in TCPRelay class
        virtual void handleDNSResolved(std::string hostname, std::string ip, \
                int error) = 0;
};

 

相似问题:https://stackoverflow.com/questions/8951884/undefined-reference-to-typeinfo-for-class

发表评论

电子邮件地址不会被公开。 必填项已用*标注

17 − 6 =

− 1 = 1