从CMakeLists.txt在子目录中填充$ {SRCS} [英] Populating ${SRCS} from CMakeLists.txt in subdirectories
问题描述
我目前在我的项目根目录中的 CMakeLists.txt
文件中定义了一个 $ {SRCS}
列出我的可执行文件所需的每个源文件:
SET(SRCS main.cpp
dir1 / file1.cpp
dir1 / file2.cpp
dir2 / file3.cpp
dir2 / file4.cpp)
如何将这个列表分布在每个子目录中的 CMakeLists.txt
文件中?这是:
CMakeLists.txt
将main.cpp添加到SRCS和子目录dir1和dir2
dir1 / CMakeLists.txt
将file1.cpp,file2.cpp添加到SRCS
dir2 / CMakeLists.txt
将file3.cpp,file4.cpp添加到SRCS
最好隐藏设置变量的所有细节 SRCS
在CMake 宏。然后可以在所有项目CMake列表文件中调用宏以添加源。
在项目根文件夹中的 CMakeLists.txt
中,添加以下宏定义:
宏(add_sources)
文件(RELATIVE_PATH _relPath$ {CMAKE_SOURCE_DIR}$ {CMAKE_CURRENT_SOURCE_DIR})
foreach _src $ {ARGN})
if(_relPath)
list(APPEND SRCS$ {_ relPath} / $ {_ src})
else $ {_ src})
endif()
endforeach()
if(_relPath)
#将SRCS传播到父目录
set(SRCS $ {SRCS} PARENT_SCOPE )
endif()
endmacro()
add_sources(main.cpp)
add_subdirectory(dir1)
add_subdirectory(dir2)
b $ b消息(STATUS$ {SRCS})
宏首先计算源文件相对于每个参数的项目根目录。如果宏是从项目子目录内部调用的,则变量SRCS的新值需要通过使用 PARENT_SCOPE 选项。
在子目录中,您可以简单地添加宏调用在 dir1 / CMakeLists.txt
中添加:
add_sources file2.cpp)
并在 dir2 / CMakeLists.txt
add:
add_sources(file3.cpp file4.cpp)
/ pre>
I currently define a
${SRCS}
variable in theCMakeLists.txt
file in my projects root directory, listing every source file required for my executable:SET (SRCS main.cpp dir1/file1.cpp dir1/file2.cpp dir2/file3.cpp dir2/file4.cpp)
How can I distribute this list across the
CMakeLists.txt
files in each of the subdirectories? That is:CMakeLists.txt Adds main.cpp to SRCS and subdirectories dir1 and dir2 dir1/CMakeLists.txt Adds file1.cpp, file2.cpp to SRCS dir2/CMakeLists.txt Adds file3.cpp, file4.cpp to SRCS
解决方案It's best to hide all the details of setting up the variable
SRCS
in a CMake macro. The macro can then be called in all the project CMake list files to add sources.In the
CMakeLists.txt
in the project root folder, add the following macro definition:macro (add_sources) file (RELATIVE_PATH _relPath "${CMAKE_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}") foreach (_src ${ARGN}) if (_relPath) list (APPEND SRCS "${_relPath}/${_src}") else() list (APPEND SRCS "${_src}") endif() endforeach() if (_relPath) # propagate SRCS to parent directory set (SRCS ${SRCS} PARENT_SCOPE) endif() endmacro() add_sources(main.cpp) add_subdirectory(dir1) add_subdirectory(dir2) message(STATUS "${SRCS}")
The macro first computes the path of the source file relative to the project root for each argument. If the macro is invoked from inside a project sub directory the new value of the variable SRCS needs to be propagated to the parent folder by using the PARENT_SCOPE option.
In the sub directories, you can simply add a macro call, e.g. in
dir1/CMakeLists.txt
add:add_sources(file1.cpp file2.cpp)
And in
dir2/CMakeLists.txt
add:add_sources(file3.cpp file4.cpp)
这篇关于从CMakeLists.txt在子目录中填充$ {SRCS}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!