c++cmakearduinoavr-gcc

How to reliably determine that current CMake compiler is the avr compiler?


I could of course be lazy and determine it by path alone. But say I want a more reliable approach, like:

if(IS_AVR)
   add_compile_options(
        --arduino-avr-specific-option
    )
endif()

CMake does not support this natively, like it does with detecting windows/ios/linux. What I am doing currently is the inverse approach:

# If CMAKE_AVR_ROOT is set, I assume we compile for arduino/atmel and set the flags accordingly
if(CMAKE_AVR_ROOT)
    set(CMAKE_SYSTEM_NAME  Generic)
    # another problem with this approach is you get .exe on windows, but not linux
    # so this won't work on linux without an additional IF
    set(CMAKE_C_COMPILER ${CMAKE_AVR_BIN}/avr-gcc.exe)
    set(CMAKE_CXX_COMPILER ${CMAKE_AVR_BIN}/avr-g++.exe)
endif()

I would prefer if the CMake was set up to detect avr-gcc.exe somehow from CMAKE_C_COMPILER. Then, I'd set IS_AVR and all my conditional flags/includes would be under if(IS_AVR). This would make the CMake work with other tools that set compiler automatically.

What is an elegant way of detecting AVR target of compilation by compiler alone?


Solution

  • You can use check_c_compiler_flag.

    For example:

    
    check_c_compiler_flag(-mmcu=atmega328p IS_AVR_COMPILER)
    if(NOT IS_AVR_COMPILER)
        message(FATAL_ERROR "Detected non avr gcc")
    endif()
    

    https://cmake.org/cmake/help/latest/module/CheckCCompilerFlag.html