废话不说,直接干货:
首先touch三个文件test.h,test.c,main.c
test.c文件内容:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
int div(int a, int b)
{
return a / b;
}
test.h文件内容:
#ifndef _TEST_H_
#define _TEST_H_
extern int add(int a, int b);
extern int sub(int a, int b);
extern int mul(int a, int b);
extern int div(int a, int b);
#endif
main.c文件内容:
#include <stdio.h>
#include "test.h"
int main ()
{
int a, b;
printf("please input a and b\n");
scanf("%d%d", &a, &b);
printf("The add : %d\n", add(a, b));
printf("The sub : %d\n", sub(a, b));
printf("The mul : %d\n", mul(a, b));
printf("The div : %d\n", div(a, b));
return 0;
}
总结使用gcc生成动态库及使用动态库的方法:
step 1: 生成test.o目标文件,使用如下命令。此处需要添加-fPIC参数,该参数用于生成位置无关代码已共生成动态库使用:
[xgqin@xgqin-desktop so]$ gcc -c -o test.o -fPIC test.c
[xgqin@xgqin-desktop so]$ ls
app_static libtest.a main.c test.c test.h test.o
[xgqin@xgqin-desktop so]$ file test.o
test.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
step 2: 使用-shared参数生成动态库,使用如下命令:
[xgqin@xgqin-desktop so]$ gcc -shared -o libmyshare.so test.o
[xgqin@xgqin-desktop so]$ ls
app_static libmyshare.so libtest.a main.c test.c test.h test.o
[xgqin@xgqin-desktop so]$ file libmyshare.so
libmyshare.so: ELF 64-bit LS