Build fails with Fortran modules nammed with macros


I am working on a Fortran project that simulates generic programming (or C++ type templates) with include files and macros. We have decided to replace our home-brew build system with CMake and, up to now, things have went pretty well.

I have made a really small example that shows the issue we are running into. It’s made up of 4 files:

module GEN_NAME(trigo_)
    implicit none

    DATATYPE function square(num)
        implicit none
        DATATYPE, intent(in) :: num
        square = num * num
    end function
end module


#define DATATYPE integer
#define GEN_NAME(name) name/**/integer
#include ""
#undef GEN_NAME

#define DATATYPE real
#define GEN_NAME(name) name/**/real
#include ""
#undef GEN_NAME


program main
    use trigo_real
    implicit none
    real, parameter :: py = 3.1416
    print *, 'I make square pies: ', square(py)
end program


cmake_minimum_required(VERSION 3.16)
project(test_generic_f90 LANGUAGES Fortran)
add_executable(main ${PROJECT_F_FILES})

Building manually work fine:

gfortran -c square.F90
gfortran -o main main.F90 square.o

However, if I try to build this project with CMake, I get the following error:

Error copying Fortran module "gen_name.mod". Tried "GEN_NAME.mod" and "gen_name.mod".

It looks like CMake did not parse the macro to get the actual module name since I still see “GEN_NAME.mod” instead of “trigo_integer.mod” or"trigo_real.mod".

Is there a way I can fix this in my project or does it require changes in CMake?


1 Like