Search code examples
c++cshared-librariesldundefined-reference

g++ undefined reference to while linking with a custom shared library


I am trying to link my C++ program with a custom shared library. The shared library is written in C, however, I don't think that it should matter. My library is called libfoo.so. Its full path is /home/xyz/customlib/libfoo.so. I've also added /home/xyz/customlib to my LD_LIBRARY_PATH so ld should be able to find it. When I run nm -D libfoo.so, I get:

...
00000000000053a1 T myfunc
000000000000505f T foo
0000000000004ca9 T bar
00000000000051c6 T baz
000000000000527f T myfunc2
...

So I think that my library is correctly compiled. I am trying to link it my c++ file test.cpp by running

g++ -L/home/xyz/customlib -Og -g3 -ggdb -fsanitize=address test.cpp -o test -lfoo

However, I am getting the following errors:

/usr/bin/ld: in function sharedlib_test1()
/home/xyz/test.cpp:11: undefined reference to `myfunc()'
/usr/bin/ld: in function sharedlib_test2()
/home/xyz/test.cpp:33: undefined reference to `foo()'
...

What am I doing wrong? How can I resolve this? Note that I have renamed the files and the shared library as I cannot share the exact file and function names.


Solution

  • As indicated by the comments in the post, it turns out that I was missing the extern "C" in the header file. So in my code, I wrapped my include statement in an extern "C" which solved the issue.

    TLDR: The header include in the code should look like:

    extern "C"      // Import C style functions 
    {
            #include <foo.h>
    }