在makefile中写如下代码,生成动态库并使用
dmain:dmain dmain.c dmain.o dtest.c dtest.o
gcc -c dtest.c
gcc -shared -fPIC -o libdtest.so dtest.o
gcc -c dmain.c
gcc -o dmain dmain.o ./libdtest.so
.PHONY: clean
clean:
-rm -rf *.o dmain *.so
上述代码将dtest.c编译出的中间目标文件dtest.o生成动态库libdtest.so ,再用dmain链接libdtest.so进行使用;
[~/]$ make
利用上述命令执行makefile文件,结果如下:
/usr/bin/ld: dtest.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
dtest.o: could not read symbols: Bad value
collect2: error: ld returned 1 exit status
make: *** [dmain] Error 1
解决方法:在gcc -c detest.c 后加 -fPIC,代码如下:
dmain:dmain dmain.c dmain.o dtest.c dtest.o gcc -c -fPIC dtest.c gcc -shared -fPIC -o libdtest.so dtest.o gcc -c dmain.c gcc -o dmain dmain.o ./libdtest.so
重新执行make,无报错!