方法一:
有test.h,test1.c,test2.c,main.c,其中:
1 // main.c 2 #include "test.h" 3 4 void main(){ 5 test1(); 6 test2(); 7 }
生成.so: gcc test1.c test2.c -fPIC -shared -o libtest.so
调用.so: gcc main.c -L. -ltest -o main
export LD_LIBRARY_PATH=/home/linden/projects //LD_LIBRARY_PATH的意思是告诉loader在哪些目录中可以找到共享库. 可以设置多个搜索目录, 这些目录之间用冒号分隔开
./main即可
方法二:
1 //test.h 2 3 #include "stdio.h" 4 void test1(); 5 void test2();
1 //test1.c 2 3 #include "stdio.h" 4 void test1(){ 5 printf("this is test11111111...\n"); 6 }
1 //test2.c 2 3 #include "stdio.h" 4 void test2(){ 5 printf("this is test22222222...\n"); 6 }
1 //main.c 2 3 #include "stdio.h" 4 #include "stdlib.h" 5 #include "dlfcn.h" 6 #include "test.h" 7 8 void main(){ 9 void *SoLib; 10 int (*So)(); 11 SoLib = dlopen("./libtest.so",RTLD_LAZY); ////加载libtest.so 12 So = dlsym(SoLib,"test1"); //声名test1方法
13 (*So)(""); //执行test1方法 14 return; 15 }
生成.so文件:gcc test.h test1.c test2.c -fPIC -shared -o libtest.so
调用.so文件:gcc main.c -o test -ldl
浙公网安备 33010602011771号