编译目标代码时指定的动态库搜索路径(指的是用-wl,rpath或-R选项而不是-L);
gcc -Wl,-rpath,/home/arc/test,-rpath,/usr/local/lib test.c
环境变量LD_LIBRARY_PATH指定的动态库搜索路径;
export LD_LIBRARY_PATH=/root/test/env/lib
./main
或者
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./main
配置文件/etc/ld.so.conf中指定的动态库搜索路径;
更改/etc/ld.so.conf文件后记得一定要执行命令:ldconfig!该命令会将/etc/ld.so.conf文件中所有路径下的库载入内存中
默认的动态库搜索路径/lib;
默认的动态库搜索路径/usr/lib。
gcc main.c -o main -L./ -lcac
通过环境变量LIBRARY_PATH指定搜索路径
LIBRARY_PATH=.:$LIBRARY_PATH gcc main.c -o main -lcac
定义库的头文件
/*caculate.h*/
#ifndef CACULATE_HEAD_
#define CACULATE_HEAD_
//加法
int add(int a, int b);
//减法
int sub(int a, int b);
//除法
int div(int a, int b);
//乘法
int mul(int a, int b);
#endif
库中函数的实现
/*caculate.c文件*/
#include "caculate.h"
//求两个数的和
int add(int a, int b)
{
return (a + b);
}
//减法
int sub(int a, int b)
{
return (a - b);
}
//除法
int div(int a, int b)
{
return (int)(a / b);
}
//乘法
int mul(int a, int b)
{
return (a * b);
}
编译生产libcac.so文件如下: gcc -shared -fPIC caculate.c -o libcac.so
#include <stdio.h>
#include "caculate.h"
int main()
{
int a = 20;
int b = 10;
printf("%d + %d = %d\n", a, b, add(a, b));
printf("%d - %d = %d\n", a, b, sub(a, b));
printf("%d / %d = %d\n", a, b, div(a, b));
printf("%d * %d = %d\n", a, b, mul(a, b));
return 0;
}
编译运行:
gcc main.c -o main -L ./ -lcac
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./main
#include <stdio.h>
#include <dlfcn.h>
#define DLL_FILE_NAME "libcac.so"
int main()
{
void *handle;
int (*func)(int, int);
char *error;
int a = 30;
int b = 5;
handle = dlopen(DLL_FILE_NAME, RTLD_NOW);
if (handle == NULL)
{
fprintf(stderr, "Failed to open libaray %s error:%s\n", DLL_FILE_NAME, dlerror());
return -1;
}
func = dlsym(handle, "add");
printf("%d + %d = %d\n", a, b, func(a, b));
func = dlsym(handle, "sub");
printf("%d + %d = %d\n", a, b, func(a, b));
func = dlsym(handle, "div");
printf("%d + %d = %d\n", a, b, func(a, b));
func = dlsym(handle, "mul");
printf("%d + %d = %d\n", a, b, func(a, b));
dlclose(handle);
return 0;
}
编译运行
gcc call_main.c -o call_main -ldl -Wl,-rpath,./
./main
参考: