readelf --relocs foo.o | egrep '(GOT|PLT|JU?MP_SLOT)'
上句大多數時候(和平台有關)可以正確判斷是否是以fPIC選項編譯的,如果輸出為空,基本可以表明不是以fPIC選項編譯的,若有輸出,基本上表明是以fPIC選項編譯的。另外,由於靜態庫是多個目標文件的打包,所以最好把靜態庫解包之后再對每個目標文件進行判斷,這樣比較准確。
如果要用在動態庫種,o文件和a文件都應該以fPIC選項編譯。 fPIC是編譯選項也是鏈接選項,如果編譯的時候加了fPIC,鏈接的時候也必須加上。
PIC地址無關碼於非PIC碼的區別如下:
Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.
E.g. jumps would be generated as relative rather than absolute.
Pseudo-assembly:
PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2 101: JUMP_IF_EQUAL CURRENT+10 ... 111: NOP
Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2 101: JUMP_IF_EQUAL 111 ... 111: NOP
EDIT: In response to comment.
If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.
======================
ar打包命令:
第一種方法:
The first and most portable way is to use libtool. After having built the other libraries also with libtool, you can combine them just by adding the .la libs to an automake libaz_la_LIBADD variable, or directly from a Makefile with something like:
libtool --mode=link cc -static -o libaz.la libabc.la libxyz.la
第二種方法:
you'd have to unpack into different directories and repack again, to avoid replacing overlapping member names:
mkdir abc; cd abc; ar -x ../libabc.a
mkdir xyz; cd xyz; ar -x ../libxyz.a
ar -cr libaz.a abc/*.o xyz/*.o
相一個a文件添加一個活多個o文件:
ar r libarith.a subtraction.o
查看a文件里的o文件:
ar t libarith.a