Applying a pre-processor macro to a single source with cmake

Hello,

I am using cmake to build my Fortran project, and I am trying to set a pre-processor macro on a single file, using set_source_files_properties. It works (the cpp flag is there when I compile the code), but cmake does not compute the dependencies properly.

Here is the sample code :

[ECA defines]$ cat CMakeLists.txt 
cmake_minimum_required (VERSION 3.22)

project (cmkpack LANGUAGES Fortran)

set_source_files_properties (a.F90 PROPERTIES COMPILE_DEFINITIONS DEF) 

add_library (AB OBJECT a.F90 b.F90)

[ECA defines]$ cat a.F90
MODULE A

CONTAINS

#ifdef DEF

SUBROUTINE RR

USE B

IMPLICIT NONE

END SUBROUTINE RR

#endif

END 
[ECA defines]$ cat b.F90
MODULE B

REAL :: X, Y, Z, T, W

CONTAINS

SUBROUTINE S
END SUBROUTINE

END 

when I run cmake and try to compile, I get this :

[ECA defines]$ cmake --version
cmake version 3.28.2

CMake suite maintained and supported by Kitware (kitware.com/cmake).
[ECA defines]$ cmake .
-- The Fortran compiler identification is GNU 4.8.5
-- Detecting Fortran compiler ABI info
-- Detecting Fortran compiler ABI info - done
-- Check for working Fortran compiler: /usr/bin/f95 - skipped
-- Configuring done (0.4s)
-- Generating done (0.0s)
-- Build files have been written to: /home/gmap/mrpm/marguina/tmp/cmk3/defines
[ECA defines]$ make VERBOSE=1
...
[ 50%] Building Fortran object CMakeFiles/AB.dir/a.F90.o
/usr/bin/f95  -DDEF   -c /home/gmap/mrpm/marguina/tmp/cmk3/defines/a.F90 -o CMakeFiles/AB.dir/a.F90.o
/home/gmap/mrpm/marguina/tmp/cmk3/defines/a.F90:9.4:

USE B
    1
Fatal Error: Can't open module file 'b.mod' for reading at (1): No such file or directory
make[2]: *** [CMakeFiles/AB.dir/a.F90.o] Error 1

So apparently, cmake fails to compute dependencies. If I remove the #ifdef/#endif in a.F90, then it works.

Is it a know feature of cmake ? (Or a bug ?) Is there a possibility to solve this problem ?

Please note that :

  • it works if I use set_target_properties on AB
  • having a.F90 and b.F90 in separate targets is not possible

Thank you for your help

This may just be per-source flags not being considered when scanning dependencies. Please file an issue for this. I can’t guarantee if/when it will be fixed beyond the desire that we have to get Fortran compilers to output P1689 files themselves (so that scanning is done by an actual Fortran compiler instead of a minimal parsing tool). But maybe adding per-source flags is feasible; needs some investigation.