Possible CMake bug w/ Fortran modules
If a Fortran source file defines a Fortran module, and that file is included in the source file list for multiple targets with add_executable()
or add_library()
a race condition can occur with CMake+Unix Makefiles when a parallel build, i.e., make -j
, is performed. During compilation errors such as
f951: Fatal Error: Can't rename module file 'tools_system.mod0' to 'tools_system.mod': No such file or directory
are encountered (GFortran 7.2 on macOS "Sierra" installed via homebrew). If the build is serialized this goes away, and as a work around a library or an "object library" can be created for the Fortran source files so that they are compiled only once.
Here is a simple CMakeLists.txt file that demonstrates this problem:
cmake_minimum_required(VERSION 3.9)
project(Fortran_RACE_REPRO C Fortran)
set(MOD_DEF_FILES basics/tools_cgnslib.f90 material/tools_material.f90 system/tools_system.f90)
foreach( file IN LISTS MOD_DEF_FILES )
list(APPEND MOD_SRCS ${CMAKE_SOURCE_DIR}/${file})
endforeach()
#add_library(mod_lib OBJECT ${MOD_SRCS})
set(i 0)
while(i LESS 20)
message(STATUS "Configuring Pi${i}")
# add_executable( Pi${i} repro_prog.f90 $<TARGET_OBJECTS:mod_lib>)
add_executable( Pi${i} repro_prog.f90 ${MOD_SRCS})
MATH(EXPR i "${i} + 1")
endwhile()
Just run this with:
export FC=gfortran-7
export CC=gcc-7
mkdir build
cd build
cmake ..
make -j
To see errors like:
Scanning dependencies of target Pi18
canning dependencies of target Pi17
[ 42%] Building Fortran object CMakeFiles/Pi8.dir/material/tools_material.f90.o
make[2]: *** [CMakeFiles/Pi13.dir/material/tools_material.f90.o.provides] Error 2
[ 43%] Building Fortran object CMakeFiles/Pi8.dir/system/tools_system.f90.o
Scanning dependencies of target Pi3
make[1]: *** [CMakeFiles/Pi13.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
f951: Fatal Error: Can't rename module file 'tools_system.mod0' to 'tools_system.mod': No such file or directory
compilation terminated.
Scanning dependencies of target Pi0
[ 44%] Building Fortran object CMakeFiles/Pi16.dir/material/tools_material.f90.o
make[3]: *** [CMakeFiles/Pi1.dir/system/tools_system.f90.o] Error 1
It is possible that this might more of a compiler bug than a CMake bug. Or perhaps it is only considered by me to be a bug. (In fact I think this is what I was told/concluded in the past, but I can't find a record of that conversation so I'm submitting it again here
Can someone please investigate, and either confirm that this is a bug, or explain why this is NOT a CMake bug?
I have attached a tarball with all the files needed: Fortran-reproducer.tar