【问题标题】:CMAKE : Link a library from a parent directoryCMAKE:从父目录链接库
【发布时间】:2020-04-21 23:46:24
【问题描述】:

这是我的树目录:

*common_folder
 \
  *main1_folder---CMakeLists.txt & file1.c & files2.c
  *
  *main2_folder
  *
  *common_librayX---file_libraryX.c (and header)
  *
  *common_libraryY--file_libraryY.c (and header)

所以我想做的是模拟以下行: gcc -Wall -o MAIN file1.c file2.c file_libraryX.c file_libraryY.c

以下是我尝试使用 CMakeLists.txt 的方法:

cmake_minimum_required(VERSION 3.0.0)
#Déclaration du projet
project(MAIN1 VERSION 1.0)

#Include headers
get_filename_component(PARENT_DIR ../ ABSOLUTE)
include_directories(${PARENT_DIR}/commonlibrayX)
include_directories(${PARENT_DIR}/commonlibraryY)

add_executable(
    MAIN1
    file1.c
    file2.c
    file_libraryX.c
    file_libraryY.c
)

install (TARGETS Project DESTINATION bin)

当然,我最终会遇到找不到文件 file_libraryX.c 和 file_libraryy.c 的错误。

我到处查找,我似乎根本不明白你如何包含来自不同目录的库(而不是标题)而不是当前 CMakeLists.txt 所在的目录。在我的例子中是父目录。

另外,为什么我在树目录中没有更高级别的 CMakeLists.txt 的原因是因为我想在每个主文件夹中创建不同的二进制文件,而不必重写 CMakeLists.txt。他们碰巧共享公共库。

有人可以帮我吗?

【问题讨论】:

  • “你如何包含来自不同目录的库(不是头文件)而不是当前 CMakeLists.txt 所在的目录。” - 只需在add_executable 命令中指定库文件的绝对路径${PARENT_DIR}/commonlibrayX/file_libraryX.c${PARENT_DIR}/commonlibraryY/file_libraryY.c
  • 非常感谢它成功了!我曾认为我需要做一些更复杂的事情,比如在每个文件夹中编写 CMakeLists.txt,但我尝试过但没有成功。你会碰巧知道怎么做吗?

标签: cmake


【解决方案1】:

现代 CMake 方法是:

common_folder/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.0)
project(MAIN1 VERSION 1.0)
add_subdirectory(common_librayX)
add_subdirectory(common_librayY)
add_subdirectory(main1_folder)

common_folder/common_librayX/CMakeLists.txt

add_library(LIBX STATIC file_libraryX.c)
target_include_directories(LIBX PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

common_folder/common_librayY/CMakeLists.txt

add_library(LIBY STATIC file_libraryY.c)
target_include_directories(LIBY PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

common_folder/main1_folder/CMakeLists.txt

add_executable(MAIN1 file1.c file2.c)
target_link_libraries(MAIN1 PRIVATE LIBX LIBY)

构建项目:

mkdir build
cd build
cmake ..
cmake --build .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多