Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix CMake Fortran modules dependency?

Hi I have a Fortran project with the following directory order

CMakeLists.txt
src/module_1.f90     (Fortran Modules)
src/module_2.f90
src/... (more files)

module_1.f90 depends on module_2.f90.

The simplified CMakeLists.txt is:

project(MyProject LANGUAGES Fortran)
file(GLOB SOURCES src/*.f90)
add_executable(MyExec SOURCES)

I get the dependency error:

Fatal Error: Can't open module file ‘module_2.mod’ :for reading at (1): The file or directory doesn't exist.

I tried:

include_directories(src)

without positive results.

if you search in the build directory:

find . -name "module_2*"

nothing exits so the module_2 is not compiled before module_1. Why this happens ?

Edited:

I found the problem at the end. In module_1 I had a pragma (which are not originally supported by Fortran) that was like:

#ifdef VAR
    module_1_function
#endif

and in my CMakeLists.txt I declared:

 set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -DVAR=2")

When CMake was creating the dependency tree it was not taking into account this variable. To do it right I had to do the last in the following way:

 add_definitions(-DVAR=2)

This solved the problem.

like image 997
gagiuntoli Avatar asked Jan 21 '26 13:01

gagiuntoli


1 Answers

Instead of putting all .mod files into one directory, for larger projects, there is a cleaner solution, defining a function:

function(add_fortran_library LIB)
    add_library(${LIB} ${ARGN})

    # set module path to LIB_DIR/mod
    get_target_property(LIB_DIR ${LIB} BINARY_DIR)
    set_target_properties(${LIB} PROPERTIES Fortran_MODULE_DIRECTORY ${LIB_DIR}/mod)

    # making LIB_DIR/mod available for libraries linking LIB 
    target_include_directories(${LIB} INTERFACE ${LIB_DIR}/mod)
endfunction(add_fortran_library)

If you now use add_fortran_library() instead of add_library() you don't have to care about the modules anymore.

like image 179
Libavius Avatar answered Jan 23 '26 07:01

Libavius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!