Cmake:为多配置 cmake 项目指定配置特定设置 [英] Cmake: Specifiy config specific settings for multi-config cmake project

查看:113
本文介绍了Cmake:为多配置 cmake 项目指定配置特定设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 Cmake 新手,我目前正在尝试将仅考虑单一配置开发的 cmake 项目转换为可以生成 Visual Studio 文件的多配置项目.

Cmake novice here, I am currently trying to convert a cmake project that was developed with only single configuration in mind to a multi-config project which can generate visual studio files.

我无法解决的问题是在 cmake 项目中存在依赖于变量 CMAKE_BUILD_TYPE 的逻辑,例如:

My problem that I can not solve is that in the cmake project there exist logic depending on the variable CMAKE_BUILD_TYPE such as:

set(ENABLE_DEBUG TRUE)
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
  set(ENABLE_DEBUG FALSE)
)

因为对于多配置 cmake CMAKE_BUILD_TYPE 是空的,这样做是行不通的.变量 ENABLE_DEBUG 然后在用于以下内容的 cmake 项目中:

Since for multi-config cmake the CMAKE_BUILD_TYPE is empty this way of doing it does not work. The variable ENABLE_DEBUG is then in the cmake project used for stuff such as:

案例 1:将库添加到仅调试配置

Case 1: Adding libraries to only debug config

if(ENABLE_DEBUG)
  list(APPEND LIB_SRC src/lib_debug.cpp)
endif()
add_library(LIB OBJECT LIB_SRC)

案例 2:将预处理器标志添加到仅调试配置

Case 2: Adding preprocessor flags to only debug config

if(ENABLE_DEBUG)
  add_definitions(...)
endif()

所以我想知道是否有人对上述一种或两种情况有解决方法,适用于多配置 cmake 项目,即,我可以指定库添加和预处理器标志,而无需依赖 CMAKE_BUILD_TYPE 变量.或者,如果有一种特定的配置方式来设置 ENABLE_DEBUG 而不依赖于 CMAKE_BUILD_TYPE 变量会更好吗?

So what I wonder is if anyone has a workaround for one or both of the cases above that would work for multi-config cmake projects, i.e so that I can specify library additions and preprocessor flags without depending on the CMAKE_BUILD_TYPE variable. Or even better if there a config specific way of setting the ENABLE_DEBUG without depending on the CMAKE_BUILD_TYPE variable?

推荐答案

在 CMake 中,用于多配置构建工具的配置特定设置的常用方法是使用 生成器表达式.

In CMake common way for config-specific settings for multi-config build tools is using generator expressions.

Command add_library 允许对源文件使用生成器表达式.例如.这个:

Command add_library allows to use generator expressions for source files. E.g. this:

add_library(mylib common.c $<$<CONFIG:DEBUG>:debug.c>)

创建一个由所有配置中的 common.c 加上 Debug 配置中的附加 debug.c 组成的库.

creates a library consisted from common.c in all configuration plus additional debug.c in Debug configuration.

add_definitions 的文档没有说明生成器的用法表达式,但 target_compile_definitions 的文档:

Documentation for add_definitions doesn't note usage of generator expressions, but documentation for target_compile_definitions does:

target_compile_definitions(mylib PUBLIC $<$<CONFIG:DEBUG>:-DDEBUG_VAR>)

这篇关于Cmake:为多配置 cmake 项目指定配置特定设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆