How to create a C #define for a certain target using CMake?

后端 未结 3 1727
面向向阳花
面向向阳花 2020-12-30 01:45

I feel a little stupid right now. After recently converting a few smaller projects to use CMake, I decided to also get rid of a few \"Platform_Config.h\" files. These files

相关标签:
3条回答
  • 2020-12-30 02:27

    In case you want to set defines per target: Since 2.8.11 you can use target_compile_definitions.

    In earlier versions you probably don't want to use set_target_properties as is, since it overwrites any defines you set previously. Call get_target_property first instead, then merge with previous values. See add_target_definitions here.

    0 讨论(0)
  • 2020-12-30 02:29

    There are two options. You can use the add_definitions method to pass defines as compiler flags: E.g. somewhere in your projects cmakelists.txt:

    add_definitions( -DUSE_NEW_CACHE )
    

    CMake will make sure the -D prefix is converted to the right flag for your compiler (/D for msvc and -D for gcc).

    Alternatively, check out configure_file. It is more complex, but may be better suited to your original approach with a Platform_Config file.

    You can create an input-file, similar to your original Platform_Config.h and add "#cmakedefine" lines to it.

    Let's call in Platform_Config.h.in:

    // In Platform_Config.h.in
    #cmakedefine USE_NEW_CACHE
    // end of Platform_Config.h.in
    

    When then running

    configure_file( ${CMAKE_SOURCE_DIR}/Platform_Config.h.in ${CMAKE_BINARY_DIR}/common/Platform_Config.h )
    

    it will generate a new Platform_Config file in your build-dir. Those variables in cmake which are also a cmakedefine will be present in the generated file, the other ones will be commented out or undefed.

    Of course, you should make sure the actual, generated file is then correctly found when including it in your source files.

    0 讨论(0)
  • 2020-12-30 02:37

    option command might provide what you are looking for.
    use it with the COMPILE DEFINITIONS property on the target and i think you are done. To set the property on the target, use the command set target properties

    option(DEBUGPRINTS "Prints a lot of debug prints")
    target(myProgram ...)
    if(DEBUGPRINTS)
    set_target_properties(myProgram PROPERTIES COMPILE_DEFINITIONS "DEBUGPRINTS=1")
    endif()
    

    edit:

    The option i wrote in the example shows up as a checkbox in the CMake GUI.

    0 讨论(0)
提交回复
热议问题