Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export macros in Fortran

I'd like to mimic C code in a simple fortran project, where I would #define some macros and use them in my code.

For instance, an animal module would be as follows:

#define timestwo(x) (2 * (x))

module animal_module

    implicit none

    ! ...

    ! test
    procedure :: answer

    ! ...

    function answer(this) result(n)
        class(animal), intent(in) :: this
        integer :: n
        n = timestwo(42)
    end function answer
end module animal_module

If I use the macro in the module, as you can see, I have no errors and it works just fine.

However, using that macro in the main file doesn't work at all:

program oo

    use animal_module

    implicit none

    print *, 'the macro ', timestwo(5)

end program

With the compiler complaining about the macro:

main.F90(21): error #6404: This name does not have a type, and must have an explicit type.   [TIMESTWO]
    print *, 'the macro ', timestwo(5)

What am I missing?

like image 464
senseiwa Avatar asked Mar 03 '23 06:03

senseiwa


2 Answers

When using pre-processor macros, the effect is a simple text replacement in that file. The source file of the question does not create any module entity which can be exported, and replacements do not propagate up "use chains".

Fortran differs from C in that use module is not the same thing as #include "header.h": the source code for the module is not included in the main program's file for text replacement to occur.

If you really which to use this approach you should repeat the macro definition on the program's source. To simplify things, you can define this common macro in a pre-processor include file and #include it (not include):

#include "common_macros.fi"
program
...
end program

and similar in your module file.

Better would be to move away from using pre-processor macros to implement "simple functions". A real function in the module would be an exportable entity. A pure function that simple is highly likely to be inlined (with appropriate optimization flags) just as easily as a macro.

like image 58
francescalus Avatar answered Apr 21 '23 10:04

francescalus


Here is some example code that works in a console application

#define twice(x) (2*x)

program Console1
implicit none

print *, twice(7)
! 14

end program Console1

which you need to compile with the /fpp option

enter image description here

like image 41
John Alexiou Avatar answered Apr 21 '23 10:04

John Alexiou