I’ve got a project that has the following directory structure
my_cool_project/
CMakeLists.txt
source1/
CMakeLists.txt
foo.f90
bar.f90
source2/
CMakeLists.txt
baz.f90
qux.f90
source3/
CMakeLists.txt
bif.f90
bof.f90
main.f90
The main program is written in main.f90, which calls subroutines defined in the other source files. Some of these source files define modules, while others are naked subroutines. There are dependencies between the directories, such that each one cannot be built independently. I am struggling to write a CMakeLists.txt that automagically figures out the dependency graph and builds the main program.
My top-level CMakeLists.txt is:
# my_cool_project/CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(my_cool_project Fortran)
set(CMAKE_Fortran_MODULE_DIRECTORY ${CMAKE_BINARY_DIR/mod})
add_subdirectory(source1)
add_subdirectory(source2)
add_subdirectory(source3)
While the lower ones are
# my_cool_project/source1/CMakeLists.txt
set(SRC ${SRC} foo.f90 bar.f90)
# my_cool_project/source2/CMakeLists.txt
set(SRC ${SRC} baz.f90 qux.f90)
# my_cool_project/source2/CMakeLists.txt
set(SRC ${SRC} bif.f90 bof.f90)
add_executable(${PROJECT_NAME} main.f90 ${SRC})
When I try to build this project, the source files are not built in the right order, so module dependencies are not fulfilled, and compilation fails. It is as if CMake doesn’t recognize that there are dependences across directories. I know the dependency graph is solvable because I have been able to build this project with a plain Makefile together with the tool makedepf90
. Have I done something stupid in my setup here?
I know the simplest workaround would be to flatten the directory structure – dump everything under a single source directory, and then have just two CMakeLists.txt files for the whole project. But for external reasons, it is important to me to preserve the source directory structure here. Given that constraint, how to I coerce CMake into building this project?
I’ll happily provide more detail if needed. Many thanks in advance to any Fortran CMake wizards who can help.