将子目录中的 Source 添加到 cmake 项目 [英] Add Source in a subdirectory to a cmake project
问题描述
我有一个没有被分成库的项目,但是源代码被组织在一个目录树中.我不知道如何告诉 cmake 进入一个目录,然后将该目录中的源添加到父目录中定义的项目中.我尝试了以下操作:
I have project which has not been divided into libraries, but the source is organized in a directory tree. I do not know how to tell cmake to go down a directory, then add the source in that directory to project defined in the parent directory. I have attempted the following:
在 project/source/CMakelists.txt 中:
in project/source/CMakelists.txt:
set(SOURCE
${CMAKE_CURRENT_SOURCE_DIR}/unitTest/main.cpp
)
add_subdirectory("${PROJECT_SOURCE_DIR}/folder1")
add_executable(UnitTestRNG ${SOURCE} ${HEADERS})
然后在 project/source/folder1/CMakeLists.txt 中:
then in project/source/folder1/CMakeLists.txt:
set(SOURCE
${SOURCE}
${CMAKE_CURRENT_SOURCE_DIR}/file1.cpp
${CMAKE_CURRENT_SOURCE_DIR}/file2.cpp
)
set(HEADERS
${HEADERS}
${CMAKE_CURRENT_SOURCE_DIR}/file1.hpp
${CMAKE_CURRENT_SOURCE_DIR}/file2.hpp
)
使用一些 message() 语句,我发现子文件夹将获取 SOURCE 变量的内容,但该变量的新赋值不会在返回父 CMakeLists.txt 时持续存在
using some message() statements, I have found that the the child folder will get the contents of the SOURCE variable, but it's new assignment to that variable will not persist on returning to the parent CMakeLists.txt
寻找示例和 cmake 教程使我得出以下结论:- 项目中的源文件结构通常是扁平的- 如果代码是分文件夹的,一般是分到相应的库中.
Looking for examples and at the cmake tutorial has led me to the conclusion that: - Source file structures are usually flat within a project - If code is divided into folders, it is usually is divided into corresponding libraries.
我想知道是否有一些最佳实践"让我在尝试这种结构时有所偏离.
I wonder if there is some "best practice" from which I am deviating by attempting this structure.
推荐答案
从 CMake 3.1 开始,有一种从子目录添加源代码的新方法:target_sources
Since CMake 3.1 there is a new way to add source from subdirectories: target_sources
假设您有 root_dir
和 root_dir/sub_dir
以及两者中的源文件.使用 target_sources
你可以这样做:
Say you have root_dir
and root_dir/sub_dir
and source files in both. With target_sources
you can do this:
在root_dir/CMakeLists.txt
中定义目标
add_library(some_target main.cpp)
add_subdirectory(sub_dir)
在root_dir/sub_dir/CMakeLists.txt
中添加源:
target_sources(some_target PRIVATE more_cool_stuff.cpp)
some_target
现在将包含两个源文件.
some_target
will now contain both source files.
也可以使用root_dir/sub_dir/CMakeLists.txt
中的其他命令使用some_target
,例如target_compile_definitions
,非常方便添加编译定义.
It is also possible to use other commands in root_dir/sub_dir/CMakeLists.txt
using some_target
, for example target_compile_definitions
which is quite convenient to add compilation definitions.
我了解了 target_sources
这里,如果您需要更多解释和示例,请查看
这篇关于将子目录中的 Source 添加到 cmake 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!