Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force unused function to export in shared library

Tags:

c++

gcc

printme() and getme() defined in top.cpp and top.h

I used printme() function in test.cpp (test cpp file) in main function

g++34 -c top.cpp -fPIC    
ar rcs libtop.a top.o    
g++34 -c test.cpp -fPIC

g++34 -shared -o ltop.so -ltop -L. -fPIC   

getme is not getting exported in ltop.so

How i can force getme function exported in ltop.so When i do nm ltop.so
it is not showing getme symbol
i want to force this

Note: file can have multiple unused function like - getme()
I want to force all to export to so library

like image 364
Avinash Kumar Avatar asked Oct 20 '25 18:10

Avinash Kumar


2 Answers

Normally, when linking with a static library only the modules in the static library that contain an unresolved symbol end up getting linked.

Here, since there is no unresolved reference to getme(), hence this module does not get linked from the static library. The solution is to explicitly make it unresolved.

A minor complicating factor is the C++ symbol name mangling. It is necessary to figure out what is the mangled symbol name for the getme() function. The easiest way is to look at the library with the nm command:

$ nm libtop.a

top.o:
0000000000000000 T _Z5getmei

Ok, so the mangled symbol name is _Z5getmei. The -u linker flag forces an unresolved reference to the indicated symbol to be used when linking:

g++ -shared -o ltop.so -L. -ltop -Wl,-u -Wl,_Z5getmei

The documentation for the -u option is found in the ld man page. This includes the module in the shared library:

$ nm ltop.so | grep getme
0000000000000680 T _Z5getmei
like image 85
Sam Varshavchik Avatar answered Oct 23 '25 07:10

Sam Varshavchik


Don't use your static library to create your dynamic one. Instead, use the component object file directly:

g++34 -shared -o ltop.so -fPIC top.o

The reason is that when you specify a library with -l when compiling a binary, only unresolved external symbols from earlier in the compilation line are picked up. In your case, this is nothing, so precisely nothing is picked up in creating libtop.so from libtop.a

UPDATE: As an alternative, if the original object files are no longer available, youc an use the --whole-archive linker option to force it to include everything from a static library, rather than just unresolved externals:

g++34 -shared -o ltop.so -fPIC -Wl,--whole-archive ./libtop.a

Or:

g++34 -shared -o ltop.so -fPIC -Wl,--whole-archive -L. -ltop
like image 23
Smeeheey Avatar answered Oct 23 '25 06:10

Smeeheey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!