我的编译环境 ubuntu desktop 16.04
一:测试代码
测试有3个文件:AB.h,AB.c,test.c
//AB.h void hello(); //AB.c #include <stdio.h> void hello() { printf("hello from AB.c \n"); } //test.c #include <stdio.h> #include "AB.h" void main(void) { printf("it is main\n"); hello(); }
使用gcc, 编译运行,显示结果:
[email protected]:~/Desktop/demo$ gcc AB.c test.c
[email protected]:~/Desktop/demo$ ./a.out
it is main
hello from AB.c
二:gcc 编译静态类库 .a
//编译点o文件 [email protected]:~/Desktop/demo$ gcc -c AB.c //编译为AB.o文件 [email protected]:~/Desktop/demo$ ls AB.c AB.h AB.o a.out test.c //打包成.a 文件 [email protected]:~/Desktop/demo$ ar -crv libAB.a AB.o a - AB.o //编译测试程序,测试libAB.a [email protected]:~/Desktop/demo$ gcc -o testlibA test.c libAB.a //测试程序 testlibA [email protected]:~/Desktop/demo$ ls AB.c AB.h AB.o a.out libAB.a test.c testlibA //运行测试,输出结果与上面一致 [email protected]:~/Desktop/demo$ ./testlibA it is main hello from AB.c [email protected]:~/Desktop/demo$
三:gcc 编译动态类库 .so
//编译AB.c 为动态类库libAB.so [email protected]:~/Desktop/demo$ gcc -shared -o libAB.so -fPIC AB.c //查看 [email protected]:~/Desktop/demo$ ls AB.c AB.h AB.o a.out libAB.a libAB.so test.c testlibA //编译测试程序testSO,并链接当前目录下的libAB.so [email protected]:~/Desktop/demo$ gcc -o testSO test.c -lAB -L. //设置一下动态类库路径 [email protected]:~/Desktop/demo$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH //运行测试程序,结果与上述一致 [email protected]:~/Desktop/demo$ ./testSO it is main hello from AB.c [email protected]:~/Desktop/demo$
对外提供,只需要把 AB.h 和libAB.a 或libAB.so 即可;
参考:http://www.cnblogs.com/ymy124/archive/2012/04/13/2446434.html
时间: 2024-10-09 22:33:53