英文:
Filtering configurations with CMake for Visual Studio 2022
问题
你好,我试图为我的项目添加特定于配置的定义,但它似乎不按我预期的方式工作。如果我在运行CMake时指定配置,我的代码可以正常工作,但这在Visual Studio中会让事情变得有些奇怪,因为如果我像下面的代码一样指定-DCMAKE_BUILD_TYPE=Debug,它将将“TestingDebug”定义添加到Visual Studio中的所有配置,这不是我想要的。
if (CMAKE_BUILD_TYPE STREQUAL Debug)
add_definitions(-DTestingDebug)
endif()
if (CMAKE_BUILD_TYPE STREQUAL Release)
add_definitions(-DTestingRel)
endif()
是否有一种方法可以一次生成所有这些定义,以便在Visual Studio中更改配置时它将具有正确的定义?
我尝试过使用cmake --build {builddir} --config {config}
命令,因为我在某处读到应该在尝试为多配置工具构建时使用它。下面是我用于我的项目的代码,但似乎也不起作用,我不知道是不是用错了,还是我需要做其他事情。
cmake -S ../ -B ../Build/
cmmake --build ../Build/ --config Debug
cmake --build ../Build/ --config Release
英文:
Hello im trying to add configuration specific definitions to my project but it doesn't seem to work the way i expect it to.
My code works fine if i specify the configuration when i run cmake however this makes it a bit weird in visual studio since if i have something like the code below and specify -DCMAKE_BUILD_TYPE=Debug it will add the 'TestingDebug' define to all my configurations in visual studio which is not what i want.
if (CMAKE_BUILD_TYPE STREQUAL Debug)
add_definitions(-DTestingDebug)
endif()
if (CMAKE_BUILD_TYPE STREQUAL Release)
add_definitions(-DTestingRel)
endif()
Is there a way to generate all of these at onces so when i change configuration in visual studio it will have the correct defines?
i've tried using the cmake --build {builddir} --config {config}
command because i read somewhere thats what you're supposed to use when trying to build for multi-configuration tools. The code below is what i used for my project but it doesn't seem to work either, idk if im just using it wrong or if there is something else i need to do.
cmake -S ../ -B ../Build/
cmake --build ../Build/ --config Debug
cmake --build ../Build/ --config Release
答案1
得分: 1
你可以使用add_compile_definitions
,它支持生成表达式(generator expressions)。例如,以下代码将在 Debug 配置下添加 TestingDebug
,在 Release 配置下添加 TestingRelease
。
add_compile_definitions(Testing$<CONFIG>)
此外,你还可以在生成表达式中使用条件。以下代码将在 Debug 配置下添加 TestingDebug
,在其他任何配置下添加 TestingNotDebug
:
add_compile_definitions($<IF:$<CONFIG:Debug>,TestingDebug,TestingNotDebug>)
更多详情请参考:https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html
英文:
You can use add_compile_definitions
which supports generator expressions. For example this one will add TestingDebug
for Debug configuration and TestingRelease
for Release.
add_compile_definitions(Testing$<CONFIG>)
Also you can use conditions inside generator expressions. This one will add TestingDebug
for Debug configuration and TestingNotDebug
for any other configuration:
add_compile_definitions($<IF:$<CONFIG:Debug>,TestingDebug,TestingNotDebug>)
More details: https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论