在Fortran中导出宏

sen*_*iwa 4 fortran fortran90

我想在一个简单的fortran项目中模拟C代码,在该项目中我将#define使用一些宏并将其用于我的代码中。

例如,动物模块如下:

#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
Run Code Online (Sandbox Code Playgroud)

如您所见,如果我在模块中使用了宏,则没有错误,并且可以正常工作。

但是,在主文件中使用该宏根本不起作用:

program oo

    use animal_module

    implicit none

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

end program
Run Code Online (Sandbox Code Playgroud)

编译器抱怨宏:

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

我想念什么?

fra*_*lus 6

使用预处理器宏时,效果是该文件中的简单文本替换。问题的源文件不会创建任何可导出的模块实体,并且替换不会在“使用链”上传播。

选自C的Fortran不同之处在于use module不象同样的事情#include "header.h":该模块的源代码不包含在主程序的文件以发生文本替换。

如果确实要使用哪种方法,则应在程序源上重复宏定义。为简化起见,您可以在预处理器包含文件及其中定义此公共宏#include(不是include):

#include "common_macros.fi"
program
...
end program
Run Code Online (Sandbox Code Playgroud)

并在您的模块文件中类似。

最好不要使用预处理器宏来实现“简单功能”。模块中的实际功能是可导出实体。简单的纯函数很可能像宏一样容易地内联(带有适当的优化标志)。