Search code examples
cmakepreprocessor

Is there a way to add_definitions for just a single language?


CMake provides add_compile_definitions() for adding compiler definitions for all targets in the current directory; and there is also target_compile_definitions() for individual targets. But - it seems to me like the general case should be language-specific, not absolutely all targets. Why would, say, C and Rust use the same definitions?

So - is there some way to add a definition to all targets of a single language, other than one-at-a-time?


Solution

  • Try using add_compile_definitions at the top of the top-level CMakeLists.txt file (or whichever variable scope you want this to apply to) with the $<COMPILE_LANGUAGE:languages> generator expression (requires cmake_minimum_required(VERSION 3.3)). Ex.

    add_compile_definitions("$<$<COMPILE_LANGUAGE:C,CXX>:-DFOO>")
    

    If your cmake_minimum_required is less than 3.3, I suppose you could append to CMAKE_<LANG>_FLAGS. Ex.

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DFOO=bar")