dlopen未定义参考

时间:2019-08-16 17:52:06

标签: c++ cmake

我对使用CMake构建的以下C ++代码有疑问:

#include <iostream>
#include <dlfcn.h>

int main() {
    void* vulkanLibrary = dlopen( "libvulkan.so.1", RTLD_NOW );
    if(vulkanLibrary) return 0;
    else return 1;
}

这里是CMakeLists:

cmake_minimum_required(VERSION 3.14)
project(VulkanTest)

set(CMAKE_CXX_STANDARD 17)

add_link_options(-ldl)
add_executable(VulkanTest main.cpp)

构建输出:

/opt/JetBrains/CLion-2019.2/bin/cmake/linux/bin/cmake --build /home/eriksimon/CLionProjects/VulkanTest/cmake-build-debug --target VulkanTest -- -j 4
-- Configuring done
-- Generating done
-- Build files have been written to: /home/eriksimon/CLionProjects/VulkanTest/cmake-build-debug
[ 50%] Linking CXX executable VulkanTest
/usr/bin/ld: CMakeFiles/VulkanTest.dir/main.cpp.o: in function `main':
/home/eriksimon/CLionProjects/VulkanTest/main.cpp:5: undefined reference to `dlopen'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/VulkanTest.dir/build.make:84: VulkanTest] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/VulkanTest.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/VulkanTest.dir/rule] Error 2
make: *** [Makefile:118: VulkanTest] Error 2

我将dlopen上的链接器错误报告为未定义引用。谷歌搜索时,我只发现帖子告诉要与“ -ldl”链接器标志链接。好像我在CMake文件中设置了它。链接器不使用它的原因是什么?

2 个答案:

答案 0 :(得分:1)

您没有正确链接到dl库。您正在使用预定义的CMake变量CMAKE_DL_LIBS寻找target_link_libraries命令:

cmake_minimum_required(VERSION 3.14)
project(VulkanTest)

set(CMAKE_CXX_STANDARD 17)

add_executable(VulkanTest main.cpp)
target_link_libraries(VulkanTest ${CMAKE_DL_LIBS})

答案 1 :(得分:0)

好像您没有正确使用CMake。 add_link_options被定义为

  

在链接步骤中为可执行文件,共享库或模块添加选项   当前目录中下添加的库目标   

重点是我的。在定义可执行文件之前,您需要先放入add_link_options