本文结合自己编写的cJSON Makefile进行简单说明。
Makefile文件内容如下:
-------------------------------------------------------------------
all: libcjson.so test
libcjson.so: cJSON.o
cc -shared -o libcjson.so cJSON.o # 添加 -shared 参数
test: test.o
cc -o test test.o -lm -L./ -lcjson # -L 指定动态库所在的路径
cJSON.o: cJSON.h cJSON.c
cc -fpic -c cJSON.c # 添加 -fpic 参数
test.o: test.c
cc -c test.c
clean:
rm -rf *.o *.so test
libcjson.so: cJSON.o
cc -shared -o libcjson.so cJSON.o # 添加 -shared 参数
test: test.o
cc -o test test.o -lm -L./ -lcjson # -L 指定动态库所在的路径
cJSON.o: cJSON.h cJSON.c
cc -fpic -c cJSON.c # 添加 -fpic 参数
test.o: test.c
cc -c test.c
clean:
rm -rf *.o *.so test
-------------------------------------------------------------------
# ./test // 直接运行会出现如下错误
./test: error while loading shared libraries: libcjson.so: cannot open shared object file: No such file or directory
解决方法:
方法一:将 *.so 拷贝至 /lib 或 /usr/lib 目录;
方法二:执行 export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH,将 *.so 所在路径,即当前路径添加到环境变量中。
由此可见,动态库在程序链接和运行时都需要使用。