Accessing VTABLE directily issues undefined error

139 views Asked by At

I was experimenting with virtual table and virtual pointer. To know more I did the following:

  //a simple class
  class X
  {
  public:
       // fn is a simple virtual function
       virtual void fn() { cout << "n = " << n << endl; }
       // a member variable
       int n;
  };

  int main()
  {
     // create an object (obj) of class X
     X *obj = new X();
     obj->n = 10;

     // get the virtual table pointer of object obj
     int* vptr =  *(int**)obj;

     __asm__("mov %eax, obj;");

     // function fn is the first entry of the virtual table, so it's vptr[0]
     ((void (*)()) vptr[0])();

     // the above should be the same as the following
     //obj->fn();

     return 0;
  }

But compiler is giving the following error:

/home/OaVTND/cclnoQaK.o: In function 'main': prog.cpp:(.text.startup+0x26): undefined reference to `obj'
collect2: error: ld returned 1 exit status

I am not familiar with assembly language code. I borrowed this from some body else's code. I am using gcc-4.9 and Centos 7 x64 bit server.

2

There are 2 answers

8
Volodymyr Boiko On BEST ANSWER

obj is a local variable, it has no linkage, no symbol. just try to make your object global.

3
yugr On

Just get rid of inline asm and do

((void (*)(void *)) vptr[0])(&obj);

Warning: I assume that you run on gcc Linux x86_64 as ABI details on other platforms will be different.