Undefined reference to vtable

前端 未结 16 2527
死守一世寂寞
死守一世寂寞 2020-11-21 20:30

When building my C++ program, I\'m getting the error message

undefined reference to \'vtable...

What is the cause of this probl

16条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 21:26

    I think it's also worth mentioning that you will also get the message when you try to link to object of any class that has at least one virtual method and linker cannot find the file. For example:

    Foo.hpp:

    class Foo
    {
    public:
        virtual void StartFooing();
    };
    

    Foo.cpp:

    #include "Foo.hpp"
    
    void Foo::StartFooing(){ //fooing }
    

    Compiled with:

    g++ Foo.cpp -c
    

    And main.cpp:

    #include "Foo.hpp"
    
    int main()
    {
        Foo foo;
    }
    

    Compiled and linked with:

    g++ main.cpp -o main
    

    Gives our favourite error:

    /tmp/cclKnW0g.o: In function main': main.cpp:(.text+0x1a): undefined reference tovtable for Foo' collect2: error: ld returned 1 exit status

    This occure from my undestanding becasue:

    1. Vtable is created per class at compile time

    2. Linker does not have access to vtable that is in Foo.o

提交回复
热议问题