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[1], "%u", &x);
  sscanf(argv[2], "%u", &y);

  long long res = sth(x, y);//调用共享库文件的定义的函数
  printf("answer is %u\n", res);
  return 0;
}

生成库文件:

首先使用 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 5 6
answer is 41

猜你喜欢

转载自www.cnblogs.com/ming-4/p/11853705.html