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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With