Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link a C++ shared library with gcc

I have seen a GCC link with a C++ shared library, but I am not able to reproduce it on my own. So first I create a C++ library with a testfunction:

g++ -shared -o libtest.so test.c

Then I have a test main function which calls the library function and compile it like this

gcc -o prog.out main.c -L. -ltest

Then i receive the error

undefined reference to 'testfunc'

which i think is caused by different refernce in the library ... C names the function testfunc and C++ names the function [some stuff]__testfunc[maybe again some stuff].

I have also tried to use

gcc -o prog.out main.c -l:libtest.so

but this results in the same error.

Therefore, my question is: How is it possible to link a c++ library with gcc to a c file?

Update: I know i can use extern "C", but that's not the way it is solved. Maybe there are some parameters for the linker instead?

Update2: Just thought it could also be possible that the first part is just compiled with c++ and linked with gcc. Also tried this:

g++ -c testlib.c -o testlib.o
gcc -shared -o libtest.so testlib.o
gcc -o prog.out -l:libtest.so

still doesn't work. Is there something wrong with the flags?

like image 678
marty bourque Avatar asked Dec 26 '22 22:12

marty bourque


1 Answers

Yes, the problem has nothing to do with shared libraries (I think...) and everything to do with name mangling.

In your header, you must declare the function like this:

#ifdef __cplusplus
extern "C" {
#endif

void testfunc(void);

#ifdef __cplusplus
}
#endif

This will cause testfunc to have the same symbol and calling conventions for both C and C++.

On the system I'm using right now, the C symbol name will be _testfunc and the C++ symbol name (assuming you don't use extern "C") will be __Z8testfuncv, which encodes information about the parameter types so overloading will work correctly. For example, void testfunc(int x) becomes __Z8testfunci, which doesn't collide with __Z8testfuncv.

like image 185
Dietrich Epp Avatar answered Jan 05 '23 18:01

Dietrich Epp