其他语言中是否有类似的“COMMON”实现,Fortran的引用环境?
Fortran 语言有一个称为 COMMON 的引用环境。
正如下面网站中所定义的,COMMON 语句定义了一个主内存存储块,以便不同的程序单元可以共享相同的数据,而无需使用参数。
https://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vn7v/index.html
示例实现如下所示:
我想知道在其他语言(如 C、Python 或 Java)中是否有此类环境的类似实现,以及它与 Global 环境有何不同。
回答
我试图在评论中压缩所有内容。但这没有用。所以这里有一个更广泛的答案。
公共块在现代 Fortran 中很少使用,它的使用早已被弃用。至少在过去的 3 年里,modules 一直是 Fortran 中数据共享的官方正确方式。Python 和 Fortran 中模块的实用程序几乎相同(尽管 Python 模块作为文件夹层次结构的组织方式比 Fortran 中的要灵活一些)。这是一个例子
module dataSharing
real :: exampleModuleVariable = 0.
end module dataSharing
program main
call print()
end program main
subroutine print()
use dataSharing, only: exampleModuleVariable
write(*,*) "exampleModuleVariable before = ", exampleModuleVariable
exampleModuleVariable = 1.
write(*,*) "exampleModuleVariable after = ", exampleModuleVariable
end subroutine print
但在 Fortran 模块之前,特别是在 FORTRAN77 中,数据共享的主要方法是通过称为公共块的存储区域。可以通过以下语法定义公共存储区域(可以命名或未命名):
program main
real :: exampleModuleVariable = 0.
common / dataSharing / exampleModuleVariable
call print()
end program main
subroutine print()
common / dataSharing / exampleModuleVariable
write(*,*) "exampleModuleVariable before = ", exampleModuleVariable
exampleModuleVariable = 1.
write(*,*) "exampleModuleVariable after = ", exampleModuleVariable
end subroutine print
以上两个代码(一个带有module,另一个带有common)在功能上是等效的。但这种module风格比其他较旧的 F77 已弃用方法更受欢迎。如果您遵循 Fortran 模块风格,则将其转换为 Python 模块应该相当容易,因为这两种语言的概念非常相似,尽管语法略有不同。我不认为 C 是否有任何可与公共块相媲美的东西,当然也没有模块的概念。但是,C++20 最近在 C++ 中添加了模块的概念。
最后一件事:Oracle F77 手册太旧了,不能依赖,除了维护旧的 F77 代码。Intel、HP/Cray 和 IBM Fortran 手册非常现代,它们的编译器支持现代 Fortran (2018/2008/2003) 的全部或大部分最新功能。GNU、NAG 和 NVIDIA Fortran 编译器也是如此。
- External variables are the closest thing C has to common (or module variables)
- Even more preferred would be to encapsulate the subroutine print within the module. Best would be to encapsulate the subroutine, and not make any data visible from the module. Variables in global scope are bad.