参考 链接 https://blog.csdn.net/Goforyouqp/article/details/132106168
/* ---------- h.h 文件 -------------- */
#ifndef H_H
#define H_H
void print(void);
#endif
/* ---------- h.c 文件 -------------- */
#include "h.h"
#include <stdio.h>
void print(void)
{
printf("hh\n");
}
/* ---------- main.c 文件 -------------- */
#include "h.h"
#include <stdio.h>
int main()
{
print();
return 0;
}
1. 编译动态库:
gcc -shared -fpic -o libh.so h.c -fPIC 生成位置无关的代码
2. 链接动态库
gcc -o main main.c -L . -lh -L 指库路径 -l 指定库的名称
在当前路径下面 也可以直接使用 gcc main.c libh.so -o main1 省略 参数。
3. 程序运行
设置临时环境变量,否则找不到动态库:
export LD_LIBRARY_PATH=/home/liu/Desktop/c-demos/c-demos/shared:$LD_LIBRARY_PATH
./main
在库里面 设置回调函数,把回调函数暴露到外面给用户自己实现。
在库里面 void print(void) 函数里面调用 回调函数 print_cb();
基于上述代码修改如下:
/* ---------- h.c 文件 修改-------------- */
#include "h.h"
#include <stdio.h>
extern void print_cb(void);
void print(void)
{
print_cb();
}
/* ---------- cb.c 回调函数所在的文件-------------- */
#include <stdio.h>
int print_cb(void)
{
printf("hello cb!\n");
}
编译:
1. 编译动态库:
gcc -shared -fpic -o libh.so h.c -fPIC 生成位置无关的代码
2. 链接动态库
gcc -o main main.c -L . -lh -L 指库路径 -l 指定库的名称
3. 程序运行
设置临时环境变量,否则找不到动态库:
export LD_LIBRARY_PATH=/home/liu/Desktop/c-demos/c-demos/shared:$LD_LIBRARY_PATH
./main