首页 > 解决方案 > 向所有 CMake 目标添加额外的源文件?

问题描述

如何将多个源文件添加到所有 CMake add_executable()(又名目标)?

  1. 我只是在编写类似于自动化 CMake 脚本的东西,因此我对普通项目中定义的任何目标名称(或变量)一无所知。

  2. 我知道关于我想要添加的源文件的一切。

  3. 我的脚本将在其他正常项目中进行include()编辑。CMakeLists.txt

除了遍历每个目标之外BUILDSYSTEM_TARGETS,是否有一种优雅的方法可以做到这一点?target_sources()

我已经看到将源文件添加到某些特定目标的解决方案: 一旦定义,可以将更多源文件添加到可执行文件吗?


要详细说明我想要做什么,请检查:

# my_script.cmake
some_magic_function_that_adds_sources_to_all_targets(
  abs_path_to_file1.cpp
  abs_path_to_file2.cpp
)
# CMakeLists.txt (of some other projects)
cmake_minimum_required(VERSION 3.7)
project(project_name)

include(abs_path_to_my_script.cmake)  # can be anywhere in this file

add_executable(exe1        
               exe1.cpp)

add_executable(exe2        
               exe2.cpp)

add_executable(i_dont_know_exec_name 
               i_dont_know.cpp 
               how_many_files.cpp
               are_here.cpp)

因此,CMakeLists.txt将在功能上等同于:

# CMakeLists.txt (of some other projects)
cmake_minimum_required(VERSION 3.7)
project(project_name)

add_executable(exe1        
  exe1.cpp
  abs_path_to_file1.cpp 
  abs_path_to_file2.cpp
)

add_executable(exe2        
  exe2.cpp
  abs_path_to_file1.cpp 
  abs_path_to_file2.cpp
)

add_executable(i_dont_know_exec_name 
  i_dont_know.cpp 
  how_many_files.cpp
  are_here.cpp
  abs_path_to_file1.cpp 
  abs_path_to_file2.cpp
)

标签: cmake

解决方案


推荐阅读