Reputation: 777
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
Upvotes: 4
Views: 2067
Reputation: 10316
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
Upvotes: 2
Reputation: 118330
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
Upvotes: 2