【问题标题】:CMake How to access headers and source files in a different folderCMake如何访问不同文件夹中的头文件和源文件
【发布时间】:2021-02-12 20:55:34
【问题描述】:

我有一个如下图所示的代码库。我正在尝试添加一个新的独立可执行文件。 main.cppCMakeLists.txt 文件位于 folder4main.cpp 需要来自 folder3 的代码。

目前我正在使用:

cmake_minimum_required(VERSION 3.10)

# set the project name
project(Standalone)

# add the executable
add_executable(StandaloneExe main.cpp)

我现在应该使用file( GLOB SRCS *.cpp *.h )folder3 检索头文件和源文件吗?

我只想要生成这个可执行文件的最简单方法。

【问题讨论】:

    标签: cmake


    【解决方案1】:

    我现在应该使用文件(GLOB SRCS *.cpp *.h)从文件夹 3 中检索头文件和源文件吗?

    不,您应该永远使用GLOB 来获取资源。更多详细信息请参见我的答案:https://stackoverflow.com/a/65191951/2137996

    我只想要生成这个可执行文件的最简单方法。

    请将您的 CMakeLists.txt 放在根目录中。然后写:

    cmake_minimum_required(VERSION 3.10)
    
    # set the project name
    project(Standalone)
    
    # add the executable
    add_executable(
      StandaloneExe
      folder2/folder4/main.cpp
      folder1/folder3/a.cpp
      folder1/folder3/b.cpp
    )
    
    # Might need this, maybe not, depending on your includes
    target_include_directories(
      StandaloneExe
      PRIVATE 
        "${CMAKE_CURRENT_SOURCE_DIR}/folder1/folder3"
    )
    

    如果你绝对不能移动你的列表文件,那么你可以使用绝对路径:

    add_executable(
      StandaloneExe
      ${CMAKE_CURRENT_LIST_DIR}/../../folder2/folder4/main.cpp
      ${CMAKE_CURRENT_LIST_DIR}/../../folder1/folder3/a.cpp
      ${CMAKE_CURRENT_LIST_DIR}/../../folder1/folder3/b.cpp
    )
    

    【讨论】:

    • 谢谢亚历克斯。请问一下包含的条件是什么?而且我不能将 CMakaeLists 放在根目录中,因为那里已经有一个用于另一个可执行文件。这只是系统一部分的一个小独立。
    • 如果你有,例如。 #include <a.h> 在 main.cpp 中,您可能需要设置包含路径。
    • 我刚刚尝试了 target_include_directories 并且我得到了 Cannot specify include directory for target ........ 这不是由这个项目构建的
    • 基本上我正在尝试创建一个独立的可执行文件,它将运行代码库的一小部分。这就是为什么我想在子文件夹中找到 CMakeList 和 main.cpp
    • @user997112 如果没有看到您的 CMakeLists.txt,我不能说为什么会发生这种情况,但这可能只是一个错字。或者你在 add_executable 之前调用了它
    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多