g++ undefined reference to typeinfo

cdleary picture cdleary · Nov 21, 2008 · Viewed 186.3k times · Source

I just ran across the following error (and found the solution online, but it's not present in Stack Overflow):

(.gnu.linkonce.[stuff]): undefined reference to [method] [object file]:(.gnu.linkonce.[stuff]): undefined reference to `typeinfo for [classname]'

Why might one get one of these "undefined reference to typeinfo" linker errors?

(Bonus points if you can explain what's going on behind the scenes.)

Answer

paxdiablo picture paxdiablo · Nov 21, 2008

One possible reason is because you are declaring a virtual function without defining it.

When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).

An example of defining the virtual function is:

virtual void fn() { /* insert code here */ }

In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.

The line

virtual void fn();

declares fn() without defining it and will cause the error message you asked about.

It's very similar to the code:

extern int i;
int *pi = &i;

which states that the integer i is declared in another compilation unit which must be resolved at link time (otherwise pi can't be set to it's address).