【C】——动态库中函数的作用范围

  如何生成动态库 net小伙 已经在此文中说明——【C】——如何生成静态库和动态库;接下来就要看看动态库中函数的作用范围;

  首先我们使用命令   gcc -fPIC -shared -o libtest.so test.c 生成一个动态库 —— libtest.so。 test.c 代码如下(一个很简单的输出函数):

#include <stdio.h>
#include <string.h>
void test(void){
    printf("the test is the shared lib
");
}

  然后编写两个文件 hello.c main.c 分别如下:

1 #include <stdio.h>
2 #include <stdlib.h>
3 void test(void){
4     printf("hello this is test
");
5 }
1 #include <stdio.h>
2 #include <stdlib.h>
3 
4 int main(int argc, char *argv[]){
5     test();
6     return 0;
7 }

  使用命令 gcc main.c hello.c -ltest -L=./testlib/ 编译生成 a.out 可执行文件。

  ./a.out 执行程序显示结果如下:[执行程序之前必须使用 export LD_LIBRARY_PATH=libtest.so 所在目录]

  the test is the shared lib 

  可见程序优先执行 hello.c 中的 test 函数。

  如果使用 gcc main.c -ltest -L=./testlib/ 编译生成 a.out ,然后执行 ./a.out 结果如下:the test is the shared lib;  

原文地址:https://www.cnblogs.com/ngnetboy/p/4158573.html