Can CPP preprocessing statement in Fortran be inde

2019-01-20 18:40发布

问题:

I am fairly new to use Fortran preprocessing statement and have a question which is probably pretty native. Can Fortran preprocessing statement be indented? I tested using Gfortran 4.8.1 on Linux (openSUSE Leap) and it turned out I it can not be indented at all.

The following code main.f90 works with gfortran -cpp main.f90 -o main:

program main
    implicit none
#ifdef DEBUG
    print *, "I am in debug mode"
#endif 
    print *, "hello world!"
end program main

But the following throws an error:

program main
    implicit none
    #ifdef DEBUG
    print *, "I am in debug mode"
    #endif 
    print *, "hello world!"
end program main

The error message is Error: Invalid character in name at (1). Does this mean that we should always write the preprocessing statement from the first beginning of the line or it is just a compiler specific rule? Any help would be greatly appreciated and thanks in advance!

回答1:

No, they cannot be indented because gfortran runs CPP in traditional mode which does not allow indentation. They must always start in the first column.

You could run CPP manually, but be very very careful about that. If you use the // string concatenation operator somewhere the preprocessor would treat it as a comment. You must use the -C flag as shown by @ewcz in his/her answer which disables discarding of comments.

Some compilers supply their own FPP preprocessor which behaves differently.



回答2:

you could use the C preprocessor to do the processing and then compile the processed file, i.e., assuming that your program is in main.f90, then something like:

cpp -nostdinc -C -P -w main.f90 > _main.f90
gfortran -o main _main.f90

In this connection, this question is quite useful: Indenting #defines