測試代碼
hello.c hello.h
makefile:
CFLAGS = -g -O2 -Wall -Werror -Wno-unused -fPIC
CXXFLAGS = -fPIC -shared
hello.o:hello.c hello.h
gcc -c $(CFLAGS) $(CXXFLAGS) hello.c
libhello.so:hello.o
ar cr libhello.a hello.o
staticlib:hello.o
ar cr libhello.a hello.o
dynamic:hello.o
gcc hello.o $(CXXFLAGS) -o libhello.so
all:libhello.so
echo "compile start..."
gcc -fPIC -shared -o libhello.so hello.h -Wl,--whole-archive libhello.a -Wl,--no-whole-archive
clean:
rm *.o *.a
靜态庫:
ar cr libhello.a hello.o
動态庫:
gcc hello.o $(CXXFLAGS) -o libhello.so
靜态->動态
gcc -fPIC -shared -o libhello.so hello.h -Wl,--whole-archive libhello.a -Wl,--no-whole-archive
注意:
在将靜态庫轉為動态庫的過程中,一定要保證在編譯靜态庫的時候加上了 -fpic編譯選項,不然會出現
‘/usr/bin/ld: libhello.a(hello.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
libhello.a(hello.o): error adding symbols: Bad value collect2: error: ld returned 1 exit status‘ 錯誤資訊。