CMake: Set different name for #cmakedefine variable

﹥>﹥吖頭↗ 提交于 2019-12-02 14:52:53

问题


I know you can use CMake's configure_file to make CMake variables available to your program. For example, I can use

#define ${CMAKE_BUILD_TYPE}

resulting in

#define Release

However, to keep my code more readible, I would prefer to define

#define BUILD_TYPE_RELEASE

Is there a simple way to achieve this?


回答1:


Here is a fairly simple way to solve it:

In CMakesLists.txt:

if (NOT CMAKE_BUILD_TYPE)
    set (CMAKE_BUILD_TYPE Release)
endif (NOT CMAKE_BUILD_TYPE)

string (TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE_NAME)

configure_file (config.h.in config.h)

And in config.h.in:

#define BUILD_TYPE_${BUILD_TYPE_NAME}

I am, however, still curious if there is a more elegant solution.




回答2:


This is more a question of your preferred programming style (configuration files vs. compiler definitions).

In your case I would use add_definitions() or directly modify/append COMPILE_DEFINITIONS directory property (using generator expressions also supports multi-configuration environments):

set_property(
    DIRECTORY 
    APPEND 
    PROPERTY 
        COMPILE_DEFINITIONS "BUILD_TYPE_$<UPPER_CASE:$<CONFIG>>"
)

Most simplified Debug/Release Check

You can also check what compiler definitions CMake does pre-define. Without having to modify/add something to your CMakeLists.txt files you could simply check for NDEBUG definition (set for Release builds across platforms) in you C/C++ code:

#ifdef NDEBUG
... 
#endif

References

  • CMake: How to pass preprocessor macros
  • How to check if a CMake build directory build type is Debug or Release?
  • What predefined macro can be used to detect debug build with clang?


来源:https://stackoverflow.com/questions/38780863/cmake-set-different-name-for-cmakedefine-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!