23,217
社区成员




//lib1.h
#ifndef __LIB1_H__
#define __LIB1_H__
int lib1_hello(void);
#endif
//////////////////////////////////
//lib1.c
#include <stdio.h>
int lib1_hello(void)
{
printf("hello this function is in lib1\n");
return 0;
}
//////////////////////////////////
//lib2.h
#ifndef __LIB2_H__
#define __LIB2_H__
int call_lib1_func(void);
#endif
//////////////////////////////////
//lib2.c
#include "lib1.h"
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int call_lib1_func(void)
{
void* handle = NULL;
int (*lib1func)(void);
handle = dlopen("liblib1.so", RTLD_LAZY);
if (!handle) {
printf("%s\n", dlerror());
exit(EXIT_FAILURE);
}
lib1func = dlsym(handle, "lib1_hello");
lib1func();
return 0;
}
//////////////////////////////////
//main.c
#include "lib2.h"
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
void* handle = NULL;
int (*lib2func)(void);
handle = dlopen("liblib2.so", RTLD_LAZY);
if (!handle) {
printf("%s\n", dlerror());
exit(EXIT_FAILURE);
}
lib2func = dlsym(handle, "call_lib1_func");
lib2func();
return 0;
}
//////////////////////////////////
//Makefile
all:lib1 lib2
gcc -g -Wall main.c -ldl -L. -llib2
lib1:
gcc -g -Wall -shared -fPIC lib1.c -o liblib1.so
lib2:
gcc -g -Wall -shared -fPIC lib2.c -o liblib2.so
//set env
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:2个so文件的绝对路径
//执行 a.out
hello this function is in lib1