• CMake: ELF文件加载动态库的位置


    简单工程示例

    1. world.c

    #include<stdio.h>  
    void world(void)
    {  
        printf("world.
    ");  
    } 

    2. hello.c

    #include <stdio.h> 
     
    void world(void);  
    void hello(void) 
    {  
        printf("hello
    ");  
        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(LINK_PATH .)
    SET(LINK_PATH . )
    
    INCLUDE_DIRECTORIES(${INCLUDE_PATH})
    LINK_DIRECTORIES(${LINK_PATH})
    
    LINK_LIBRARIES(hello world -Wl,-rpath=/usr/local/lib)
    ADD_EXECUTABLE(main main.c)

    或者方案二

    cmake_minimum_required(VERSION 3.2)
    PROJECT(pro)        
    
    SET(CMAKE_BUILD_TYPE Release)
    
    SET(LINK_PATH .)
    SET(LINK_PATH . /usr/local/lib)
    
    INCLUDE_DIRECTORIES(${INCLUDE_PATH})
    LINK_DIRECTORIES(${LINK_PATH})
    
    ADD_EXECUTABLE(main main.c)
    TARGET_LINK_LIBRARIES(main hello world)

    或者方案三

    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})
    
    SET(CMAKE_EXE_LINKER_FLAGS '-Wl,-rpath=/usr/local/lib')
    LINK_LIBRARIES(hello world)
    ADD_EXECUTABLE(main main.c)

    通过设置连接参数,将/usr/local/lib和当前文件夹路径写入到ELF文件内,则每次ELF将在/usr/local/lib路径下查找可执行文件

  • 相关阅读:
    jQuery实现动态搜索显示功能
    面试
    Struts1和Struts2的区别和对比(完整版)
    JAVA调用增删改的存储过程
    Spring MVC入门
    jQuery Ajax通用js封装
    js ==与===区别
    shell脚本awk
    C++对象模型初窥
    再见,2021
  • 原文地址:https://www.cnblogs.com/flyinggod/p/8027447.html
Copyright © 2020-2023  润新知