Home > Blockchain >  c Linker error undefined reference to vtable
c Linker error undefined reference to vtable

Time:01-22

I'm trying to write a small C inheritance program, after compiling succeeds, the linker fails in the derived of a derived class, C.o, stating

relocation against `_ZTV26C' in read-only section `.text'

and

undefined reference to `vtable for C'

can anyone see what am i missing?

A.h

#ifndef A_H_
#define A_H_
#include <string>
#include <iostream>
using namespace std;

class A {
protected:
    string name;
public:
    A(string name);
    virtual ~A();
    virtual void justATest(){}
    void justBecause();
    virtual bool derivedTest(){}
};

#endif /* A_H_ */

A.cpp

#include "A.h"

A::A(string name) {this->name.assign(name);}

A::~A() {}

void A::justBecause(){}

B.h

#ifndef B_H_
#define B_H_
#include "A.h"
#include <string>

class B : public A{
public:
    B(string name):A(name){}
    virtual ~B(){}
    bool derivedTest();
};

#endif /* B_H_ */

B.cpp

#include "B.h"
bool B::derivedTest()
{
    return true;
}

C.h

#ifndef C_H_
#define C_H_
#include "B.h"

class C : public B{
public:
    C(string name) :B(name){}
    virtual ~C(){}
    void justATest();
};

#endif /* C_H_ */

C.cpp

#include "C.h"
void C::justATest()
{
    cout<< this->name;
}

main.cpp

#include "C.h"
int main(int argc, char* argv[]) {
    C* c = new C("str");
return 0;
}

the exact error message is: /usr/bin/ld: ./main.o: warning: relocation against _ZTV1C' in read-only section .text._ZN1CC2ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE[_ZN1CC5ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE]' /usr/bin/ld: ./main.o: in function C::C(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)': /home/some_user/eclipse-workspace/demo_proj/Debug/../C.h:14: undefined reference to vtable for C' /usr/bin/ld: warning: creating DT_TEXTREL in a PIE

CodePudding user response:

After many hours of debugging, and countless tries, with the same error message i found the answer. This is C linker crooked way of telling me there is an unimplemented method in one of my classes. adding to c.h

bool derivedTest() override;

and to c.cpp

bool C::derivedTest(){return false;}

p.s another nice way of finding the problem is adding override after each message in the header file, the compiler is much clearer

CodePudding user response:

Please update your original question with the linker command and error message from the comments section.

To me it seems you are not using g for linking but rather ld. Configure eclipse to use g for linking your C source code then it should work.

  • Related