技术宅和经济盲

Monday, February 28, 2011

Error of "Undefined reference to: XXX"...

Wow, waste some hours (in fact some days in total in the past, because don't know the root cause very clearly before!), and now I can wrote some summary on this error. It dues to two reasons: (at least in gcc-3.4)
- Forgot to link library with func XXX.
- Order of libraries is wrong!

Most of Google result mentioned the first case, but for the second one, it is really difficult to catch. It happens like you have some components, like A, B, C. A depends on B and C depends on A and B. And we will use libA / libB / libC to replace library of A / B / C. So, if you have command like:

g++-3.4 -o <binary> <objects> ...libB libA

then you will found libA can't find functions defined in libB. It often makes you confused, but in fact, the only problem is the order, you can try

g++-3.4 -o <binary> <objs> ... libA libB

And then you found it PASSed link stage! By using "nm" command, you can get a bit hints as below:
$nm libB | grep XXX
00000000 T XXX(...)
$nm libA | grep XXX
                   U XXX(...)
From document, "T" means "a global definition", and "U" means "an external reference". If you put them into a C++ file, it should be:

void XXX(...) {
...
}

void XXX(...);

Because the later one will replace the first one in the symbol table, you can't find definition of XXX(...) any more. That is the root-cause of the problem.

So, once you failed on linking, try "nm" and think it in source code level to figure it out.

Labels:

0 Comments:

Post a Comment

<< Home