Monday, March 2, 2009

C++ undefined vtable symbol

I was recently puzzled by a student's problem using GCC to compile some C++ code. He compiled the partial code after every changes in order to make sure he didn't screw up. At one point, the code compiled but gave this linker error:
Undefined symbols:
"vtable for PRNG_Uniform", referenced from:
__ZTV12PRNG_Uniform\$non_lazy_ptr in ccBZAsss.o
collect2: ld returned 1 exit status
Searching on the web didn't yield any meaningful information about the error message. It took me a while, but I finally realized that it just means "there are some virtual methods you haven't defined; please define them."

In this particular example, the idea is to have an abstract base class PRNG (pseudo-random number generator) that derives PRNG_Uniform (uniform distributed) and other PRNGs with a variety of probability distributions (e.g. exponential, normal, or even deterministic). There is a virtual method from the base class that takes a random sample. The subclasses would implement that method. Another part of the system he implements would refer to the base class PRNG without caring what probability distribution characterizes the random samples.

The idea is that C++ compiler creates a virtual table for PRNG and each of its subclasses. The virtual table allows the method call on an object to be re-routed to the appropriate subclass implementation, even if all we have is a pointer to a PRNG object rather than to PRNG_Uniform or a specific subclass of PRNG.

In order for this virtual table to be available for the linker, all the virtual methods must be defined at link time.

Alessandro Monopoli said...

This has saved me an awful lot of time :)
Thanks!

Nitin said...

You are a savior !!!!
I was breaking my head over this for hours .. Why couldnt g++ just tell me this :) ..

Unknown said...

Nice, exactly what I was looking for - thanks!

cjwfuller88 said...

Thank you :) fixed my problem. Silly me!