1

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.

Setu
  • 180
  • 8
  • 2
    ¿Are imported functions declared as `extern "C"`? – user7860670 Oct 06 '22 at 15:07
  • https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix – Jesper Juhl Oct 06 '22 at 15:09
  • 1
    Regarding : "The shared library is written in C, however, I don't think that it should matter", you generally need to make sure the functions are declared as "extern C" in headers. – Brian McFarland Oct 06 '22 at 15:09
  • To expand on this a little bit.... Normally a dual-use C/C++ library will use `#ifdef __cplusplus` pre-processor directive, and then `extern "C"` around the entire header if true. But if you can't/don't want to modify the C-library header, you can also wrap the `#include` within your CPP source in `extern "C"`. good to be familiar with both methods if you're doing language mix & match. – Brian McFarland Oct 06 '22 at 15:17
  • I was missing the extern "C". Thanks for the help! – Setu Oct 06 '22 at 17:35

1 Answers1

1

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>
}
Setu
  • 180
  • 8