从OMake迁移至CMake:如何通过命令行参数指定编译目标组
CMake实现命令行指定目标组编译
方法一:配置阶段指定目标组(生成对应构建文件)
这种方式在运行cmake时传入参数,直接生成只包含目标组的构建系统文件,适合固定编译某组目标的场景。
- 定义目标组与所有目标
在CMakeLists.txt中先声明所有目标和对应的分组:
# 定义各个目标组 set(TARGETS_1 target_1 target_2 target_3) set(TARGETS_2 target_4 target_5 target_6) set(TARGETS_3 target_7 target_8 target_9 target_10) # 声明所有编译目标 add_executable(target_1 target_one.c) add_executable(target_2 target_two.c) add_executable(target_3 target_three.c) add_executable(target_4 target_four.c) add_executable(target_5 target_five.c) add_executable(target_6 target_six.c) add_executable(target_7 target_seven.c) add_executable(target_8 target_eight.c) add_executable(target_9 target_nine.c) add_executable(target_10 target_ten.c)
- 添加参数判断逻辑
通过缓存变量接收命令行传入的目标组参数,根据参数决定启用或禁用对应目标:
# 默认编译所有目标,允许用户通过命令行指定BUILD_GROUP set(BUILD_GROUP "all" CACHE STRING "Specify target group to build: all, group1, group2, group3") # 根据参数筛选目标 if(BUILD_GROUP STREQUAL "group1") foreach(target IN LISTS TARGETS_2 TARGETS_3) set_target_properties(${target} PROPERTIES EXCLUDE_FROM_ALL TRUE) endforeach() elseif(BUILD_GROUP STREQUAL "group2") foreach(target IN LISTS TARGETS_1 TARGETS_3) set_target_properties(${target} PROPERTIES EXCLUDE_FROM_ALL TRUE) endforeach() elseif(BUILD_GROUP STREQUAL "group3") foreach(target IN LISTS TARGETS_1 TARGETS_2) set_target_properties(${target} PROPERTIES EXCLUDE_FROM_ALL TRUE) endforeach() else() # 默认编译所有目标,确保所有目标都包含在默认构建任务中 foreach(target IN LISTS TARGETS_1 TARGETS_2 TARGETS_3) set_target_properties(${target} PROPERTIES EXCLUDE_FROM_ALL FALSE) endforeach() endif()
- 使用方式
运行cmake时指定目标组参数:
# 编译group1目标组 cmake -S . -B build -DBUILD_GROUP=group1 cmake --build build # 编译所有目标(默认行为) cmake -S . -B build cmake --build build
方法二:构建阶段指定目标组(无需重新配置)
这种方式无需重新运行cmake配置,直接在构建时通过自定义目标触发对应组的编译,更适合开发时频繁切换目标的场景。
- 定义目标组并创建自定义分组目标
# 定义各个目标组 set(TARGETS_1 target_1 target_2 target_3) set(TARGETS_2 target_4 target_5 target_6) set(TARGETS_3 target_7 target_8 target_9 target_10) # 声明所有编译目标 add_executable(target_1 target_one.c) add_executable(target_2 target_two.c) add_executable(target_3 target_three.c) add_executable(target_4 target_four.c) add_executable(target_5 target_five.c) add_executable(target_6 target_six.c) add_executable(target_7 target_seven.c) add_executable(target_8 target_eight.c) add_executable(target_9 target_nine.c) add_executable(target_10 target_ten.c) # 创建自定义分组目标,关联对应编译目标 add_custom_target(group1) add_dependencies(group1 ${TARGETS_1}) add_custom_target(group2) add_dependencies(group2 ${TARGETS_2}) add_custom_target(group3) add_dependencies(group3 ${TARGETS_3})
- 使用方式
直接在构建时指定自定义分组目标:
# 编译group1目标组 cmake --build build --target group1 # 编译group2目标组 cmake --build build --target group2 # 编译所有目标(默认行为) cmake --build build
两种方法对比
- 方法一:生成的构建文件仅包含指定组的目标,编译速度更快,适合持续集成或固定编译场景。
- 方法二:无需重新配置,可随时切换目标组,适合开发过程中频繁调整编译目标的场景。
内容的提问来源于stack exchange,提问作者Rabelo
相关产品推荐
相关产品推荐

