Race condition in CheckCXXSourceRuns ?


I notice that CheckCXXSourceRuns uses file(WRITE ...) to generate a source file, and then uses try_compile to build the freshly generated source.

It is my (possibly wrong?) understanding that there is no explicit dependency between the code generated by file(WRITE ...) and the try_compile command, so that the try_compile may occur before the file(WRITE ... succeeds in a massively parallel build.

I ran into this exact error not in CheckCXXSourceRuns, but in nearly identical code modeled after the function, on a 40 core machine using Ninja as the generator.

Is there indeed a race condition here, or am I off the mark?

A CMake script runs sequentially. The call to try_compile() occurs later in the same script that calls file(WRITE), so the write must be complete before try_compile(). If this script is executed as part of a build rule somehow (e.g. as part of an ExternalProject), then you may have multiple scripts running simultaneously, but the project is responsible for expressing dependencies, etc. correctly so that steps are executed in the right order.

Thank you for the reply! I am at a loss as to what was happening then and will try to investigate a bit more.

The code in question is LLVM’s FindZ3.cmake (https://github.com/llvm/llvm-project/blob/master/llvm/cmake/modules/FindZ3.cmake#L4-L27) which has the same pattern, and should also be unaffected, but I was regularly having the try_compile fail because the input file was missing.

Maybe there was just an issue with the write failing in general. Is there a way to determine if file(WRITE ...) failed? My initial guess is to try reading the file back and compare content to what should be in there.