1. 三个文件
1. world.c
#include<stdio.h> void world(void) { printf("world.\n"); }
2. hello.c
#include <stdio.h> void world(void); void hello(void) { printf("hello\n"); world(); }
3. main.c
void main(void) { hello(); }
2. 编译动态库
gcc -c -fPIC hello.c world.c gcc -shared -o libworld.so world.o gcc -shared -o libhello.so hello.o -lworld -L .
可见动态库libhello.so依赖于libworld.so
3. CMakeLists.txt
cmake_minimum_required(VERSION 3.2) PROJECT(pro) SET(CMAKE_BUILD_TYPE Release) SET(LINK_PATH .) SET(LINK_PATH . ) INCLUDE_DIRECTORIES(${INCLUDE_PATH}) LINK_DIRECTORIES(${LINK_PATH}) ADD_EXECUTABLE(main main.c) TARGET_LINK_LIBRARIES(main hello world)
这种方式生成的main ELF文件的默认动态库搜索路径是当前文件夹 ".";一旦当前文件夹下动态库不存在则找不到动态库,无法执行。此时可以通过设置 LD_LIBRARY_PATH 方式帮助ELF文件在相对应路径下查找动态库或者
cmake_minimum_required(VERSION 3.2) PROJECT(pro) SET(CMAKE_BUILD_TYPE Release) SET(CMAKE_EXE_LINKER_FLAGS ‘-Wl,-rpath=/usr/local/lib‘) SET(LINK_PATH .) SET(LINK_PATH . ) INCLUDE_DIRECTORIES(${INCLUDE_PATH}) LINK_DIRECTORIES(${LINK_PATH}) ADD_EXECUTABLE(main main.c) TARGET_LINK_LIBRARIES(main hello world)
通过设置连接参数,将/usr/local/lib路径写入到ELF文件内,则每次ELF将在/usr/local/lib路径下查找可执行文件
时间: 2024-11-01 01:13:27