問題:
book@100ask:~/02_options$ arm-linux-gnueabihf-gcc -shared -o libsub.so sub.o
/home/book/100ask_am335x/ToolChain/gcc-linaro-6.2.1-2016.11-x86_64_arm-linux-gnueabihf/bin/../lib/gcc/arm-linux-gnueabihf/6.2.1/../../../../arm-linux-gnueabihf/bin/ld: sub.o: relocation R_ARM_THM_MOVW_ABS_NC against `a local symbol' can not be used when making a shared object; recompile with -fPIC
sub.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
解決方案:
book@100ask:~/02_options$ arm-linux-gnueabihf-gcc -fPIC -c sub.o sub.c
sub.c: In function 'sub_fun':
sub.c:3:8: warning: implicit declaration of function 'printf' [-Wimplicit-function-decl aration]
printf("Sub fun!\n");
^~~~~~
sub.c:3:8: warning: incompatible implicit declaration of built-in function 'printf'
sub.c:3:8: note: include '<stdio.h>' or provide a declaration of 'printf'
arm-linux-gnueabihf-gcc: warning: sub.o: linker input file unused because linking not d one
book@100ask:~/02_options$ arm-linux-gnueabihf-gcc -shared -o libsub.so sub.o
book@100ask:~/02_options$
如果想創建一個動態鏈接庫,可以使用 GCC 的-shared
選項。輸入文件可以是源文件、彙編文件或者目標文件。
另外還得結合-fPIC
選項。-fPIC 選項作用於編譯階段,告訴編譯器產生與位置無關代碼(Position-Independent Code);這樣一來,產生的代碼中就沒有絕對地址了,全部使用相對地址,所以代碼可以被加載器加載到內存的任意位置,都可以正確的執行。這正是共享庫所要求的,共享庫被加載時,在內存的位置不是固定的。
-fPIC 選項作用於編譯階段,在生成目標文件時就得使用該選項,以生成位置無關的代碼。