Search code examples
cmake

How to use try_compile inside a toolchain file


Is it possible to use try_compile inside a toolchain file? I have the following code in my toolchain.cmake:

set(MAIN_SOURCE "int main() {}")
  
try_compile(
    COMPILE_RESULT
    SOURCE_FROM_VAR "main.cpp" MAIN_SOURCE
)

But unfortunately, when I try to configure my project with

cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake

it fails with:

  try_compile() works only for enabled languages.  Currently these are:

   

i.e. no languages are enabled.

Is it supposed to work at all?


Solution

  • From the CMake docs:

    CMake provides the try_compile() command and wrapper macros such as CheckSourceCompiles, CheckCXXSymbolExists and CheckIncludeFile to test capability and availability of various toolchain features. These APIs test the toolchain in some way and cache the result so that the test does not have to be performed again the next time CMake runs.

    So the answer is no.

    try_compile by definition requires a compiler. Your toolchain can set a compiler.

    You can look into using execute_process though in your cmake toolchain file.