Pattern for choosing compiler options based on toolchain?

I need to set different compiler options (using target_compile_options) depending on which toolchain is used.

What is the recommended pattern for doing so? Should I do something like this in CMakeLists.txt?

if("${CMAKE_TOOLCHAIN_FILE}" STREQUAL "gnu_arm_toolchain.cmake")
target_compile_options(${EXECUTABLE} PRIVATE

I would not assume any particular toolchain file is used unless you are in a company environment where the toolchain files are prescribed (i.e. you have to use theirs and only theirs).

For problems like the one you describe, I usually first look at whether I can use CMAKE_SYSTEM_NAME to tell me enough about the target platform. In this case, it looks like you’re targeting an embedded platform, so I wouldn’t expect CMAKE_SYSTEM_NAME to be all that useful. It could be anything, since there’s no real convention for most embedded platforms, except maybe Generic, which isn’t of use to you anyway. Similarly, CMAKE_SYSTEM_PROCESSOR is conceptually what you should be looking for, but it is very unreliable and toolchain files rarely bother to set it. Even if they did, the contents can be pretty arbitrary.

It really comes down to where might the toolchain files come from. If you want to give the user freedom to use their own toolchain file, then you can’t use the name of the toolchain file as a determinant. You could, however, potentially require the toolchain file to set a particular variable and also require that variable to have one of a prescribed set of values. That variable might be CMAKE_SYSTEM_PROCESSOR, or it might be your own custom project-specific variable. I’ve seen this used in one company’s mono repo, where it provides a set of toolchain files, but you could still use your own if you wanted to.

Based just on the example above, it looks like the options need to be set if the compiler is GCC and the target platform is ARM. Can’t this be achieved almost entirely with generator expressions?

You can detect the compiler reasonably reliably with generator expressions, but not the processor/platform. There’s no authoritative list of processor names, so you could get anything, or nothing at all.

@craig.scott @benthevining Thank you both for your answers.