测试代码
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‘ 错误信息。