【问题标题】:CMake: Link an executable to multiple libraries (*.so) [duplicate]CMake:将可执行文件链接到多个库(* .so)[重复]
【发布时间】:2020-08-12 17:29:57
【问题描述】:

我是使用 CMake 构建的新手。我正在使用 Ubuntu,并且我有一个 .cpp 文件(比如 xyz.cpp 位于 ~/mydir 中的某处),它链接到三个自定义共享库(libA.so、libB.so 和 libC.so 库)。这三个 *.so 文件位于/usr/local/lib

我想创建一个 CMakeLists.txt 来编译它。下面的脚本会抛出如下错误:

cmake_minimum_required(VERSION 3.11)
project(xyz VERSION 1.0.0 LANGUAGES C CXX)

# Set C standard to C11
set(CMAKE_C_STANDARD 11)

set(SOURCES src/xyz.cpp)

include_directories(/usr/local/include)

#For the shared library:

target_link_libraries(libA -L/usr/local/lib/)
target_link_libraries(libB -L/usr/local/lib/)
target_link_libraries(libC -L/usr/local/lib/)

target_link_libraries(xyz libA libB libC )
add_executable(xyz src/xyz.cpp)

错误:

CMake Error at CMakeLists.txt: (target_link_libraries):

   Cannot specify link libraries for target "libA" which is not built
   by this project.


 -- Configuring incomplete, errors occurred!

【问题讨论】:

  • 1) target_link_libraries 应该跟随add_executable; 2)你根本不需要target_link_libraries(libA...); 3) 添加链接目录,使用target_link_directories.

标签: c++ cmake


【解决方案1】:

几个重要的注意事项:

  1. target_link_libraries() 的第一个参数应该是由add_library()add_executable() 创建的有效CMake 目标。因此,任何target_link_libraries() 调用都应放在代码中的add_executable() 调用之后
  2. 您只需一次调用target_link_libraries() 即可将所有*.so 库链接到可执行文件。前三个调用是不必要的(并且无效,因为 libAlibBlibC 都是未定义的)。您应该提供每个库的完整路径,以确保使用正确的库。
  3. 最好在target_* 调用中包含范围参数,例如target_link_libraries()。这指定库是链接到 (PRIVATE)、添加到链接接口 (INTERFACE) 还是两者兼有 (PUBLIC)。随着您的 CMake 项目发展到包含更多目标,这种区别变得更加重要。

有了这些注释以及下面的其他一些评论,您的 CMake 文件可能看起来像这样:

cmake_minimum_required(VERSION 3.11)

# No need to specify C and CXX for LANGUAGES here, these are enabled by default!
project(xyz VERSION 1.0.0)

# Set C standard to C11
set(CMAKE_C_STANDARD 11)

set(SOURCES src/xyz.cpp)

include_directories(/usr/local/include)

# Define your executable target. You can pass in the SOURCES variable defined above.
add_executable(xyz ${SOURCES})

# Link the other libraries to your executable, using their full path.
# Note, the '-L' flag is not necessary.
target_link_libraries(xyz PRIVATE 
    /usr/local/lib/libA.so
    /usr/local/lib/libB.so
    /usr/local/lib/libC.so
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多