问题描述
当前,我需要帮助来创建CMakeList.txt
,或者只需找出cmake
命令即可。
我在同一目录中有一些源文件,分别称为A.cpp
,B.cpp
,C.cpp
,D.cpp
。我需要对它们进行编译,以使可执行文件分别命名为A,B,C,D。
我想使用CMake
自动遍历目录并生成相应的可执行文件,而不是每次添加文件时都在CMakeList.txt
中添加相应的可执行文件。
解决方法
这有点奇怪。通常我建议在需要的地方手动编写add_executable
,因为它更易于维护。
在CMake中,实际上并没有好的方式来收集目录中的所有文件。您可以使用file(GLOB ...)
来抓取所有文件;但这是在 configure 时完成的,并且,如果您引入新的源,则CMake将不会检测到新的源,也不会自动重新配置或构建新的源,而无需明确地要求进行重新配置。>
如果您能够离散列出每个来源,那会更好。但是,否则,您可以使用get_filename_component
通过每个源文件使用foreach
的组合来完成请求,以获取文件名并将其传递给add_executable
set(source_files src/a.cpp src/b.cpp src/c.cpp ...)
# Loop through each source file
foreach(source_file IN LISTS source_files)
# Get the name of the file without the extension (e.g. 'a' from src/a.cpp'
get_filename_component(target_name ${source_file} NAME_WE)
# Create an executable with the above name,building the above source
add_executable("${target_name}" "${source_file}"
endforeach()
如果无法单独列出源文件,则可以使用file(GLOB...)
or file(GLOB_RECURSE)
:
file(GLOB source_files "src/*.cpp")
但又一次;这会阻止自动检测何时添加了新资源,我不建议这样做。