linux c++ 动态加载动态库完整示例
一、源码结构
xx@xx:~/workspace/$ tree .
.
├── build
├── CMakeLists.txt
├── lib
│ ├── CMakeLists.txt
│ ├── hello.c
│ └── hello.h
└── src
├── CMakeLists.txt
├── main.c
└── main.h
3 directories, 7 files
1.创建以上源码结构
cd ~ && mkdir workspace
mkdir build && mkdir lib && src
touch CMakeLists.txt
cd lib && touch CMakeLists.txt && touch hello.c && touch hello.h
cd src && touch CMakeLists.txt && touch main.c && touch main.h
1.编辑顶层CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
PROJECT(HELLOLIB)
ADD_SUBDIRECTORY(lib)
ADD_SUBDIRECTORY(src)
2.编辑lib/CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
SET(LIBHELLO_SRC hello.c)
ADD_LIBRARY(hello SHARED ${LIBHELLO_SRC})
3.编辑lib/hello.c
#include "hello.h"
int hello_func(void)
{
printf("Hello World!\n");
return 11;
}
4.编辑lib/hello.h
#ifndef HELLO_H_
#define HELLO_H_
#include <stdio.h>
int hello_func(void);
#endif
5.编辑src/CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1)
project(main C) #项目名称 main
SET(CMAKE_C_STANDARD 11) #使用c11标准
ADD_EXECUTABLE(main main.c main.h)
TARGET_LINK_LIBRARIES(main home/xx/workspace/build/lib/libhello.so dl) #依赖的动态库,注意:libhello.so要写绝对路径
6.编辑src/main.c
#include "main.h"
#include <dlfcn.h>
#define _GNU_SOURCE
int main(){
char *error;
typedef int *(*HELLO)(void);
char file[]="/home/xx/workspace/build/lib/libhello.so";
printf("libso is %s.\n",file);
void * handle=dlopen(file,RTLD_LAZY);
if(!handle){
fprintf(stderr,"handle is null.%s\n",dlerror());
return -1;
}
HELLO obj;
//hello_func 为hello.c中的函数名称
obj=(HELLO)dlsym(handle,"hello_func");
int ret=obj();
printf("%d\n",ret);
dlclose(handle);
return 0;
}
7.编辑src/main.h
#ifndef MAIN_H
#define MAIN_H_
#include <stdio.h>
#endif
二、编译动态库和main程序
cd ~/workspace/build && cmake .. && make
三、运行main程序
cd ~/workspace/build/src && ./main
运行结果如下:
libso is /home/xx/workspace/build/lib/libhello.so.
Hello World!
11