CMake: The C Compiler is not able to compile a simple test program

CMake tries to compile an executable using “standard” (as per what CMake thinks is standard) compiler options and tries to run that executable, so to see if the compiler is working. The executable is simple like int main(int argc, char *argv[]) { return argc - 1; }.

You can’t do that when cross-compiling. Because usually you can’t link with a proper C standard library, you don’t have printf, or _start or _exit or similar, passing arguments to main is implementation-defined, or you need a special linker script, or there’s no emulator for your architecture, so can’t run cross-compiled source on the host, etc… Simply: you usually can’t run the cross-compiled executable on the host, and most of the time even the compilation is hard enough to do.

The common solution is to set before project():

set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")

So that CMake will try to compile a static library not an executable, as explained in cmake docs CMAKE_TRY_COMPILE_TARGET_TYPE. This avoids running the linker and is intended for cross-compiling.

You can set CMAKE_C_COMPILER_WORKS and it will omit the check in CMakeTestCCompiler.cmake, but CMAKE_TRY_COMPILE_TARGET_TYPE is a more proper solution.

Leave a Comment