linking problem - "undefined reference to ..."

Brian Dessent brian@dessent.net
Thu Apr 10 00:52:00 GMT 2008


Chris Bouchard wrote:

> #include "/home/theorist/cbouchrd/local/include/tsil.h"

The absolute path is a bad idea, you can simply use #include "tsil.h".

> ---------------------------------------------------------
> [cbouchrd@lx6 ~/tsil-1.1]$ g++ -t -o fig6.exe fig6.cpp -L. -ltsil
> ---------------------------------------------------------
> where I think I'm telling gcc to go to the working directory to look for library files (-L.) and then to link to libtsil.a (-ltsil).

That looks fine, although creating a binary named 'fig6.exe' on a
platform like Linux that does not typically have an extension for
executables seems really strange.  But that's neither here nor there,
and shouldn't be related to the link errors.

> /tmp/ccp26z8w.o(.text+0x96): In function `main':
> : undefined reference to `TSIL_SetParameters(TSIL_Data*, long double, long double, long double, long double, long double, long double)'

If gcc was unable to find "-ltsil" you would have gotten a different
error saying as much, so that means that it did find and search
libtsil.a for the symbol but did not find it.  You need to figure out if
indeed the library has that symbol in it.  For static archives, 'nm' is
usually used.  I like to use the idiom

nm -AP libtsil.a | grep ' T ' 

This prints the symbols	in the library, filtered on those marked 'T'
which are the functions actually contained in the library.  You can add
on an additional "| grep TSIL_SetParameters" to the end if you want to
search for that specific function.

Since this is C++ you also have to be aware of name mangling.  The
symbol will not be called as just 'TSIL_SetParameters' but some uglified
version that encodes its type.  And in fact this is why I suspect the
link is failing: in C++ due to this name mangling, libraries must all be
ABI compatible which in most cases means they must have been compiled by
the same compiler or two compatible versions of the same compiler.  In
the case of gcc this usually means they must be from the same branch,
e.g. gcc A.B.x and A.B.y.  You didn't mention if you compiled libtsil.a
yourself or got it from elsewhere, but if the latter I suspect it's not
ABI compatible.

Another related form of this problem is trying to link a C library from
C++ code.  Again, the mangling makes this impossible unless you
explicitly declare the functions as 'extern "C"' which disables the C++
calling conventions.  If the output of 'nm' doesn't show mangled
function names then the library is actually a C library and you need to
rethink how you intend to use it.  You'd need to either switch to C for
your code, or fix the tsil.h header to declare everything extern "C" if
__cplusplus is true.

Brian



More information about the Gcc-help mailing list