3

I would like to understand how the preprocessor inlines includes into the code in Fortran. With C, it's pretty simple:

Test.c:

#include <stdio.h>

int main(void) {
    return 0;
}

Then I compile using:

gcc -E test.c

Then it displays the content generated by the C preprocessor, as expected.

Now assume I have this Fortran code:

Test.f:

program test
include "mpif.h"
call mpi_init
call mpi_finalize
end

Then I run:

gfortran -E -cpp test.f // For some reason I need -cpp when using -E in Fortran

But I won't have the expected result, which is the generated include embedded into the code.

Instead, I have this:

# 1 "test.f"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "test.f"
   program test
   include  'mpif.h'

   call mpi_init

   call mpi_finalize
   end

What am I doing wrong here?

jphalimi
  • 33
  • 3
  • `-cpp` is the [Fortran preprocessing directive](http://gcc.gnu.org/onlinedocs/gfortran/Preprocessing-Options.html); if you want to preprocess the file, you need this flag. – Kyle Kanos Dec 10 '13 at 15:44

1 Answers1

3

Fortran has its own include directive which must not be confused with the preprocessor directive #include. As far as I understand it, the included code is not embedded into the master file, but the compiler instead continues to compile from the include file, and returns to the master file at the end of that file. From here:

The INCLUDE statement directs the compiler to stop reading statements from the current file and read statements in an included file or text module.

Also, included files are not preprocessed further, while #included ones are.

Note, that there is also a naming convention that enables the preprocessor only on files with capital suffixes *.F and *.F90. If you want to preprocess *.f or *.f90 files, you need to specify that in a compile option, e.g. -cpp for gfortran, and -fpp for ifort.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
  • Thanks for the answer! Is there a way to use `#include` in Fortran? – jphalimi Dec 10 '13 at 16:02
  • Yes, you can use it - you just need to make sure the preprocessor is turned on. Be aware that the preprocessor is not Standard Fortran! But at least `gfortran` and `ifort` support that. – Alexander Vogt Dec 10 '13 at 16:04
  • When I try to use `#include` in Fortran, I still don't have it inlined into the code: I use the following command: `gfortran test.F90 -E -cpp` and the include is not preprocessed – jphalimi Dec 10 '13 at 16:07
  • 1
    Make sure the `#` is in the first column! There are no blanks allowed before the hash (it is not FORTRAN syntax). – Alexander Vogt Dec 10 '13 at 16:12