Force GCC to notify about undefined references in shared libraries

Fredrik Ullner picture Fredrik Ullner · Mar 1, 2010 · Viewed 39.8k times · Source

I have a shared library that is linked with another (third-party) shared library. My shared library is then loaded using dlopen in my application. All this works fine (assuming files are in the proper path etc).

Now, the problem is that I don't even need to specify to link against the third-party shared library when I link my library. GCC accept it without reporting errors about undefined references. So, the question; how can I force GCC to notify me about undefined references?

If I change my library to be (temporarily) an executable, I get undefined references (when not supplying the library to the linker). (Works fine if I specify it.)

I.e., the following is done:

g++ -fPIC -shared -o libb.so b.o 
g++ -fPIC -shared -o liba.so a.o
g++ -o a.exe a.cpp 

Where the second line does NOT give out an error and the third line complains about an undefined reference.

Sample code:

a.h:

class a
{
public:
    void foobar();
};

a.cpp:

#include "a.h"
#include "b.h"

void a::foobar()
{
    b myB;
    myB.foobar();
}

int main()
{
    a myA; myA.foobar();
}

b.h:

class b
{
public:
    void foobar();
};

b.cpp:

#include "b.h"

void b::foobar()
{
}

Answer

Dmitry Yudakov picture Dmitry Yudakov · Mar 1, 2010

-Wl,--no-undefined linker option can be used when building shared library, undefined symbols will be shown as linker errors.

g++ -shared -Wl,-soname,libmylib.so.5 -Wl,--no-undefined \
    -o libmylib.so.1.1 mylib.o -lthirdpartylib