C语言创建共享库(动态库)步骤

时间:2023-03-09 09:33:29
C语言创建共享库(动态库)步骤

C语言创建共享库(动态库)步骤:

创建sth.c,共享库源文件:

//sth.c库源程序
unsigned long long sth(unsigned int x, unsigned int y)
{
return (x+y+x*y);
}

创建测试文件:

//test.c
#include<stdio.h>
#include<stdlib.h> int main(int argc, char *argv[])
{
unsigned int x, y;
sscanf(argv[], "%u", &x);
sscanf(argv[], "%u", &y); long long res = sth(x, y);//调用共享库文件的定义的函数
printf("answer is %u\n", res);
return ;
}

生成库文件:

首先使用 gcc 的-fPIC 选项为动态库构造一个目标文件:

gcc -fPIC -Wall -c sth.c

接下来,使用-shared 选项和已创建的目标代码,生成一个动态库libsth.so:

gcc -shared -o libsth.so sth.o

下面编译测试主程序,它将会链接到刚生成的动态库 libsth.so:

gcc -o test test.c -L . -lsth
sudo cp libsth.so /lib
./test
answer is