How/why does this work? Setup for cross-compiling and unit tests on host

Hi all, first timer here.

I am a CMake newbie and I’ve been trying to set up a project in CMake in which I can cross-compile for ARM Cortex-M targets, and compile some unit tests to run on the host machine.

In my research I stumbled upon many conflicting statements, whether CMake can’t handle multiple toolchains, whether it can, whether you need some extra shell scripts or CLI options, etc.

In the end I managed to get it to work but I have no idea why it works. The project is quite simple as it is just a template for now, you can take a look in here.

First I set up my cross-compiling toolchain as default in the root CMakeLists.txt. That works fine for the cross-compilation target.
For the host compilation what I did was just very naive and I just set the CMAKE_XXX_COMPILER variables in order to override the cross-compilation toolchain after I have declared a the project for the unit tests. It doesn’t work if you override them before the project() call.

This setup does work and compile the files correctly, but I don’t know if I’m somehow shooting myself in the foot.

I’d appreciate any feedback on this, suggestions to improve the setup, etc.
Thank you!

CMake doesn’t support multiple toolchains. Changing the CMAKE_<LANG>_COMPILER variables other than through project() or enable_language() is deep into “nothing is guaranteed” behavior. You’ll need two projects to support host and target artifacts.

1 Like

What do you mean with two “projects”? Two project() calls or two completely separate CMakeLists.txt with separate roots?

Err, sorry. I mean build directories.

You can use ExternalProject to build with a different toolchain to the main build. You would have to specify the toolchain details explicitly to avoid the main build’s details being used instead. Sorry if that’s a bit vague, low on time today, but hopefully that gives you a place to investigate next at least.

I’ll look into it, thank you :slight_smile: