在Linux上用C创建共享库so
1、创建math1.c,在命令行中输入:nano math1. c
int add(int x, int y)
{
return x+y;
}
2、编译生成共享库libmath1.so
gcc -fPIC -shared -olibmath1.so math1.c
3、创建测试程序testmath.c,在命令行中输入:nano testmath. c
#include <stdio.h>
int main()
{
int x=10, y=18;
int sum = add(x, y);
printf("%d+%d=%d\n", x, y, sum);
return 0;
}
4、编译生成测试程序testmath
gcc -otestmath -lmath1 testmath.c -L=./
5、运行测试程序,在命令行中输入:./testmath
出现找不到共享库的错误:
./testmath: error while loading shared libraries: libmath1.so: cannot open shared object file: No such file or directory
6、拷贝libmath1.so到Linux系统默认的共享库加载路径(/lib或/usr/lib)
在命令行中输入:sudo cp libmath1.so /usr/lib/
7、重新运行测试程序testmath
结果:10+18=28
关于gcc的编译参数:
-fPIC 生成与位置无关的代码,这样库就可以在任何位置被连接和装载
-shared 代表共享库
-o 链接生成指定名字的库或程序
-l 指定要链接的共享库
-L 指定共享库所在路径
1、创建math1.c,在命令行中输入:nano math1. c
int add(int x, int y)
{
return x+y;
}
2、编译生成共享库libmath1.so
gcc -fPIC -shared -olibmath1.so math1.c
3、创建测试程序testmath.c,在命令行中输入:nano testmath. c
#include <stdio.h>
int main()
{
int x=10, y=18;
int sum = add(x, y);
printf("%d+%d=%d\n", x, y, sum);
return 0;
}
4、编译生成测试程序testmath
gcc -otestmath -lmath1 testmath.c -L=./
5、运行测试程序,在命令行中输入:./testmath
出现找不到共享库的错误:
./testmath: error while loading shared libraries: libmath1.so: cannot open shared object file: No such file or directory
6、拷贝libmath1.so到Linux系统默认的共享库加载路径(/lib或/usr/lib)
在命令行中输入:sudo cp libmath1.so /usr/lib/
7、重新运行测试程序testmath
结果:10+18=28
关于gcc的编译参数:
-fPIC 生成与位置无关的代码,这样库就可以在任何位置被连接和装载
-shared 代表共享库
-o 链接生成指定名字的库或程序
-l 指定要链接的共享库
-L 指定共享库所在路径
本文介绍如何在Linux环境下使用C语言创建共享库(.so文件),并演示了具体的步骤,包括源代码编写、编译生成共享库、创建及编译测试程序,并解决了共享库加载路径的问题。
595

被折叠的 条评论
为什么被折叠?



