Dealing with multiple microcontrollers/toolchains in one code base

For a new development we are starting, we have multiple different microcontrollers on single board.
We want to maintain this codebase in one Git repository and preferably prevent duplication in the CMake configuration as well.
Although these microcontrollers have different functions, there will be an overlap in “components”/sources they will be using.

My initial thoughts are to define all the components as separate static libraries and have a different folder for each microcontroller.
I’ll still have one CMakeLists.txt in the root of the Git repository, that will include the appropriate microcontroller specific directory and all the components (as add_subdirectory doesn’t like to go up the tree).
Besides that I’ll probably have some additional script to build “all” the targets.

Does this sound like a good way to go or would you recommend another route?

Any links to articles/blogposts on this matter are also appreciated.
Just trying to figure out what the best practices are for dealing with such a situation from a CMake perspective.


Keep in mind that you can’t have multiple toolchains in the same CMake build tree. One thing you might do is have each microcontroller’s code in a separate CMake project in subdirectories in your repo, and then have your top-level project use ExternalProject (not add_subdirectory()) to run all of the separate builds.

Cc: @craig.scott

I am aware that you can not have different toolchains in the “same” build tree.
What we currently do in other projects switch between toolchains and use different build trees.
For those projects, we typically have a toolchain targeting the embedded microcontroller and another toolchain for local compilation, which we use to run unit / integration tests on the host (instead of on the microcontroller).

With ExternalProject I would be able to use different toolchains?
I should probably look into how IDEs (like VS Code) deal with this, especially since both projects will have the same components in them, but compiled using a different toolchain.
For development I’m okay with switching toolchains/build trees manually and for the CI pipeline we can just add a script that calls CMake with different arguments for the different microcontrollers, but then again, if there is a way to deal with this from within CMake, that would probably be better indeed.

Think of ExternalProject as replacing your script in the above comment. It’s basically a way of orchestrating those separate build trees you’re currently managing manually.

Although the ExternalProject sounds interesting, it seems that it does not really play nice with some IDEs, e.g. Visual Studio Code: External projects not handled as I would expect · Issue #1616 · microsoft/vscode-cmake-tools · GitHub