views:

1038

answers:

2

I'm having a linking problem. I need to link against a shared library libfoo.so that depends on a function read which I would like to define myself in the file read.c.

I compile and link everything together but at runtime I get the error

/home/bar/src/libfoo.so: undefined symbol: sread.

nm reports the symbol is defined

$nm baz | grep sread
  00000000000022f8 t sread

but ldd reports the symbol is undefined

$ldd -r baz | grep sread 
undefined symbol: sread (/home/bar/src/libfoo.so)

What gives? Is there some isse with the fact that libfoo.so is a shared library?

A: 

When you build your shared library you need to resolve all undefined symbols from either within the same library or another (shared) library. The linker will not resolve an undefined symbol from a library with a symbol from your application.

lothar
I should clarify that baz is actually a shared library. So does this mean I should create a shared library that contains only the read function, and link against this? Is there an explicit way to tell the linker to resolve the undefined symbols from the shared library libfoo.so with this other shared library (say libread.so)?
codehippo
You are quite mistaken: the runtime loader will happily resolve undefined symbol from a shared libary with a symbol from the main executable, provided that symbol is "exported" in its dynamic table (which happens e.g. when the executable is linked with -rdynamic).
Employed Russian
@codehippo you did not say that baz was a shared library and the name does not lead to that assumption either.
lothar
@Employed Russian It is very unusual to link executables with exported symbols and I did not assume that the OP was using this rare technique, as if he did he probably needed not to ask the question he did.
lothar
+6  A: 

First, defining a function called 'read' is a bad idea(TM), because it is a standard libc function on all UNIXen. The behavior of your program is undefined when you do this.

Second, the read function you defined in libbaz.so is marked with a 't' in nm output. This means that this function is local (not visible outside libbaz.so). Global functions are marked with 'T' by nm.

Did you use 'static int read(...)' when you defined it in read.c? If not, did you use a linker script, or attribute((visibility(hidden))), or perhaps -fvisibility=hidden on command line when you compiled and linked libbaz.so?

Employed Russian
the name of the function is not actually read, I was just trying to make things simple. Ahh... you are correct I am using -Wl,--version-script which includes a file that keeps all symbols local except two that I wish to export. I obviously need to export the read function as well.
codehippo