Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c++ - Linking archives (.a) into shared object (.so)

I'm compiling some shared objects file into an archive.a:

$ g++ -c -Iinclude/ -fPIC -O0 -o object1.o source1.cpp
$ g++ -c -Iinclude/ -fPIC -O0 -o object2.o source2.cpp
$ ar rvs archive.a object1.o object2.o
r - object1.o
r - object2.o

So far so good. The resulting archive.a has a good size of some KB. A dump with nm shows that the corresponding object-files are contained within the files.

Now I'm wanting to compile several of these archives into a shared object file.

g++ -g -O0 -Iinclude/ -I/usr/include/somelibrary -shared -o libLibrary.so archive1.a archive2.a

The result is that my resulting library file is nearly empty:

$ nm -D libLibrary.so
                 w _Jv_RegisterClasses
0000000000201010 A __bss_start
                 w __cxa_finalize
                 w __gmon_start__
0000000000201010 A _edata
0000000000201020 A _end
0000000000000578 T _fini
0000000000000430 T _init

Any idea what I'm doing wrong?


Edit:

When I try the switch -Wl,--whole-archive, following happens:

/usr/lib/x86_64-linux-gnu/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
(.text+0xd): undefined reference to `__init_array_end'
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libc_nonshared.a(elf-init.oS): relocation R_X86_64_PC32 against undefined hidden symbol `__init_array_end' can not be used when making a shared object
/usr/bin/ld: final link failed: Bad value
collect2: ld returned 1 exit status
make: *** [libKeynect.so] Error 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

symbols/object files in .a files that's not used, will be discarded by the linker.

Use -Wl,--whole-archive for the linking to include the entire .a file Edit, you'll need to add -Wl,--no-whole-archive after you specify your library as well, so the whole thing will be -Wl,--whole-archive archive1.a archive2.a -Wl,--no-whole-archive


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...