Search code examples
c++virtualvtableundefined-reference

can't fix undefined reference to vtable


I've been searching for a while and have found a lot of threads/pages that involve the problem I have, but I am not able to find

  1. An explanation of why this error occurs
  2. A working solution for my specific case

The following is Scanner.h:

class BaseReader {

    public:

    virtual ~BaseReader();

    virtual const char* read() = 0;
    virtual long position() = 0;
    virtual long size() = 0;
    virtual void seek(long position) = 0;

};

class CharReader : public BaseReader {

    public:

    CharReader(const char* source);
    CharReader(const char* source, long size);

    ~CharReader();

    const char* read();
    long position();
    long size();
    void seek(long position);

    private:

    char* _source;
    long _position;
    long _size;

};

In Scanner.cpp I simply implement one of the constructors of CharReader.

I use Code::Blocks, but compiling it by myself results in the exact same problem.

niklas@emerald:~/git/hiterator (CPP)$ g++ main.cpp hiterator/Scanner.cpp -o main
/tmp/cclNNwgl.o: In function `hiterator::CharReader::CharReader(char const*)':
Scanner.cpp:(.text+0x16): undefined reference to `vtable for hiterator::CharReader'
collect2: ld gab 1 als Ende-Status zurück

@qdii:

#include "Scanner.h"
using namespace hiterator;

#include <stdlib.h>
#include <string.h>

CharReader::CharReader(const char* source) {
    _size = strlen(source);
    _source = (char*) malloc(_size + 1);
    memcpy(_source, source, _size + 1);
}

Solution

  • Your program is incorrect. All virtual functions are considered used (odr-used) and thus you need to provide the definitions for all of them. Once you fix that, the issue should go away.

    The compiler is complaining that the vtable is not available. Vtable-s are an implementation detail, and thus not treated by the standard, but many compilers will generate the vtable in the translation unit that defines the first (non-inline) virtual function. In your case, whatever the criterion to generate the vtable is, you are not complying with it.