gpt4 book ai didi

c++ - CMake -- 将子目录中的所有源添加到 cmake 项目

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:55 25 4
gpt4 key购买 nike

作为这个问题的后续: Add Source in a subdirectory to a cmake project

选择子目录中的所有 .cpp 和.h 文件并将它们添加到父目录中定义的 SOURCE 变量的最佳方法是什么?


上述问题的答案示例:

set(SOURCE
${SOURCE}
${CMAKE_CURRENT_SOURCE_DIR}/file1.cpp
${CMAKE_CURRENT_SOURCE_DIR}/file2.cpp
PARENT_SCOPE
)

set(HEADERS
${HEADERS}
${CMAKE_CURRENT_SOURCE_DIR}/file1.hpp
${CMAKE_CURRENT_SOURCE_DIR}/file2.hpp
PARENT_SCOPE
)

有没有可能做这样的事情?

FILE(GLOB SUB_SOURCES *.cpp)
set(SOURCE
${SOURCE}
${CMAKE_CURRENT_SOURCE_DIR}/${SUB_SOURCES}
PARENT_SCOPE
)

将目录和子目录中的所有源代码编译成单个输出文件(而不是多个库?)的最佳方法是什么(使用 CMake?)

最佳答案

我认为您正在寻找的是 aux_source_directory 命令。

aux_source_directory Find all source files in a directory.

aux_source_directory( )

Collects the names of all the source files in the specified directory and stores the list in the provided. This command is intended to be used by projects that use explicit template instantiation. Template instantiation files can be stored in a "Templates" subdirectory and collected automatically using this command to avoid manually listing all instantiations.

It is tempting to use this command to avoid writing the list of source files for a library or executable target. While this seems to work, there is no way for CMake to generate a build system that knows when a new source file has been added. Normally the generated build system knows when it needs to rerun CMake because the CMakeLists.txt file is modified to add a new source. When the source is just added to the directory without modifying this file, one would have to manually rerun CMake to generate a build system incorporating the new file.

子目录中的 CMakeLists.txt 可能如下所示:

aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SUB_SOURCES)

set(SOURCE
${SOURCE}
${SUB_SOURCES}
PARENT_SCOPE
)

然而,正如您从文档中看到的那样,建议的做法是在 CMakeLists.txt 中单独列出文件,因为对 CMakeLists.txt 文件的更改会触发运行 cmake。

我希望这对您有所帮助并切中要点。

关于c++ - CMake -- 将子目录中的所有源添加到 cmake 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com