作者: Andy. 时间: 2016-08-20 10:07:15
介绍一下Linux中共享库的制作。
1、先来一段代码,没有主函数:
int add(int a, int b){ return a + b; }
2、加-fPIC编译,表示让gcc产生与位置无关得代码:
gcc -g -fPIC -c 1.c -o 1.o
3、加-shared链接,产生一个共享库。
gcc -shared 1.o -o lib-1.so
4、为了让Linux能找到so文件的位置,需要在.bash_profile中添加export LD_LIBRARY_PATH=$LD_LIBRARY_PATH,然后. .bash….使之生效。
5、准备一个头文件1.h:
#ifdef __cplusplus extern "C" { #endif int add(int a, int b); #ifdef __cplusplus } #endif
6、调用:
#include <stdio.h> #include "1.h" int main(){ printf("result:%d\n", add(1, 2)); }
7、.......
[[email protected] Documents]# gcc -c 2.c -o 2.o [[email protected] Documents]# gcc -L. -l1 2.o -o 2.out [[email protected] Documents]# ./2.out result:3