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

In this post, we will see how to resolve g++ undefined reference to while linking with a custom shared library

Question:

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:
So I think that my library is correctly compiled. I am trying to link it my c++ file test.cpp by running
However, I am getting the following errors:
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.

Best Answer:

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:

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com