查看目标文件是否是以-fPIC编译的, ar 打包命令将多个静态库打包到一个里面...

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

 

转载于:https://www.cnblogs.com/welhzh/p/4858139.html

你可能感兴趣的:(查看目标文件是否是以-fPIC编译的, ar 打包命令将多个静态库打包到一个里面...)