Before or after 'project' command

During setup of a CMake file in QtCreator for cross compiling, I ran into an issue whit took me quite some time to find out. ( Using CMake 3.29.2 )

Usually I put the project() command somewhere on top of the CMakelists.txt file.
In this project I had some errors, which I couldn’t explain. After some trial and error, I found out that it was caused by the following sequence.

project(myproject)
set(CMAKE_TRY_COMPILE_TARGET_TYPE “STATIC_LIBRARY”)

This resulted in the following error:

Detecting C compiler ABI info - failed
Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-gcc.exe - broken

When ‘project(myproject)’ is placed after the set() command it works as expected.

I couldn’t find anything in the documentation which explains this.

Are there more commands/statements which are expected to be before project() ?

I ran into an issue where check_language() didn’t work if placed before the project() command. I was convinced it was broken until I stumbled on the order dependency when trying to create a MVRE.

I don’t have an answer for you but I feel your pain.

Anything that relates to setting up your toolchain should go in a toolchain file. That toolchain file will be read as part of the project() command. Critically, it is also used when CMake creates a private sub-build to test the toolchain whenever a new language is enabled (by default, the first project() call will enable the C and CXX languages unless you tell it otherwise).

In your case, CMAKE_TRY_COMPILE_TARGET_TYPE needs to be set in a toolchain file. It controls how CMake tests the toolchain, so it has to be set before any languages are enabled. This is why when you tried to set it after project() it was having no effect. Resist the urge to set it within your project’s CMakeLists.txt file. It looks like you’re cross-compiling with an embedded toolchain, and for that you basically have to use a toolchain file to get the right behavior.

You might find it worthwhile to read the cmake-toolchains manual to get a bit of an introduction to some of these topics.

Thanks for your reply :smiley:
This was indeed a part which was not in the toolchain file. Its indeed listed on the toolchain file page.

Small sidenote, I also have your book, which is really nice. I was looking for this in the toolchain file section where it was not mentioned. And where basically is stated put in as little as possible. Maybe small improvement for the next print.

CMAKE_TRY_COMPILE_TARGET_TYPE is discussed in Section 24.5: Compiler Checks of the Toolchains And Cross Compiling chapter. The paragraph that mentions it doesn’t specifically talk about toolchain files, but it follows a paragraph that does. I can look at making it clearer that it would also normally only be set in a toolchain file.