Exclude targets from "all" if they are incompatible with given CMAKE_SYSTEM_PROCESSOR?


I want to ask if there’s any neat solution to the following use case in CMake. I have a project that contains:

  • x86-only code (e.g. google tests)
  • arm-only code (e.g. low-level device drivers)
  • generic code that is hardware agnostic and should be built for any platform.

Now, I’m aware that with CMake it’s only possible to built for one platform at a time, and this is selected via the toolchain file. What I’m interested in knowing is how to skip building targets that are not compatible with the platform at hand. I normally build with just make, so I guess what I’m after is connected to EXCLUDE_FROM_ALL.

For example, if I want to build for arm, I want to skip building the unit tests that only work on x86. Currently my solution is not very clean:


My CMakeLists.txts are full of those if branches and I’m looking for a cleaner solution. Preferably this information should propagate transitively (INTERFACE), i.e. if I set a low-level library to only be compatible with arm, then any other target depending on it should also only be compatible with arm.

Is there a better way of accomplishing this?


One strategy I’d consider is to put architecture-specific things under their own subdirectory. Then you choose whether to add that subdirectory based on the target platform. If structured appropriately, you may end up with fewer if(...) calls that test the target platform. Note also that I’d be wary of trusting the CMAKE_SYSTEM_PROCESSOR unless you can guarantee that it will always be set. It is very common for toolchain files to not set it.

I wouldn’t recommend always adding the targets and excluding them from the ALL target if they won’t build on the target platform. Those targets would still show up in developers’ IDEs and similar tools, which could be misleading. Another reason is that some targets may have dependencies that are not needed on other platforms. You don’t want to require dependencies you don’t need.

Thanks for the quick reply! Understood, I haven’t been up to date with the latest versions of CMake so I wanted to check if something newer has come up. I’ll continue to use if then. I am creating my own toolchain files myself for all platforms so I make sure to set CMAKE_SYSTEM_PROCESSOR properly.

Very good point about EXCLUDE_FROM_ALL, it’s indeed better that the targets don’t exist at all to reduce confusion.