How to detect target architecture using CMake?

So I devised a rather creative solution to my problem… it appears that CMake has no functionality to detect the target architecture whatsoever.

Now, we know we can easily do this in C because symbols like __i386__, __x86_64__, etc., will be defined depending on your environment. Fortunately CMake has a try_run function which will compile and run an arbitrary C source code file during the configure stage.

We could then write a small program which uses a bunch of ifdefs and writes the architecture name to the console as a string. The only problem is that this only works if the host and target system are the same… it can’t work during cross compilation because while you can compile the binary, you can’t run it to see its output.

Here’s where things get interesting. We can exploit the C preprocessor to get the necessary information by deliberately writing a broken C program… we use the original concept of writing the architecture name to the console based on ifdefs but instead of doing that, we’ll simply place an #error preprocessor directive in place of a printf call.

When CMake’s try_run function compiles the C file, compilation will always fail, but whatever message we placed in the #error directive will show up in the compiler’s error output, which try_run returns to us.

Therefore, all we have to do is parse the architecture name from the compiler’s error output using some CMake string commands, and we can retrieve the target architecture… even when cross compiling.

The OS X specific part of the code mostly uses CMAKE_OSX_ARCHITECTURES to determine the target architecture, but in the case it’s unspecified it will use the same code as other systems and correctly return x86_64 (for modern systems on which that is the compiler’s default) or i386 (for older OS X systems such as Leopard).

I’ve tested and verified this works on Windows, OS X and Linux using Visual Studio 9 and 10 generators (x86, x86_64, ia64), Xcode, NMake, MSYS Makefiles and Unix Makefiles. The correct result is returned every time.

Notice: This solution can fail if you deliberately do things like pass -m32 or -m64 to your compiler, or other flags that may affect the target architecture (is there a way to pass all environment settings through to try_run?); this is not something I’ve tested. As long as you’re using the default settings for your generator and all targets are being compiled for the same architecture you should be OK.

The full source code for my solution can be found at GitHub: https://github.com/petroules/solar-cmake/blob/master/TargetArch.cmake

Leave a Comment