gpt4 book ai didi

fortran - 如何为 Fortran 95+ 模块库提供显式接口(interface),并隐藏实现

转载 作者:行者123 更新时间:2023-12-04 23:06:36 25 4
gpt4 key购买 nike

我正在使用 gfortran 的 95+ 扩展。我有一个实用模块库,我想链接到其他项目,即作为库或共享对象/dll。但是,在 Fortran 中,我不明白如何在不维护模块接口(interface)的两个副本的情况下将接口(interface)与 Fortran 中的实现分开。

在 C 中,我会将接口(interface)与实现分开,例如:

 api.h ←includes← impl.h
↑ ↑
includes includes
↑ ↑
user.c impl.c

有没有办法在现代 Fortran 中实现相同的效果?我是否需要向我的库中的用户提供 .mod 文件?
  • 显式接口(interface)的单一定义
  • 只有接口(interface)定义暴露给用户代码

  • 编辑:总结(我认为是)答案:
  • 需要 .mod 文件,因为它们包含显式接口(interface)定义
  • 模块没有标准的 Fortran ABI —— .mod 文件将是特定于编译器的
  • 实现隐藏问题的唯一直接类似方法是子模块,它在 Fortran 2008 中定义,gfortran 不支持。
  • @High-Performance-Mark 和 Fedora 页面指出,除了避免模块之外,最实用的方法是分发仅接口(interface)模块的包含文件以及用于实现的预编译 .mods。
  • 使用包含有一些众所周知且令人讨厌的问题,包括可能重新定义常见 block 。

  • 我有点惊讶这里实际上没有一个简单的答案。

    最佳答案

    我相信你可以用 submodules 做到这一点使用 Fortran 2008 编译器。来自 FortranWiki:

    Submodules are a feature of Fortran 2008 which allow a module procedure to have its interface defined in a module while having the body of the procedure defined in a separate unit, a submodule.


    来自 Wikipedia (强调我的)

    [Submodules allow] the specification and implementation of a module to be expressed in separate program units, which improves packaging of large libraries, allows preservation of trade secrets while publishing definitive interfaces, and prevents compilation cascades.


    我对子模块没有任何经验,它们还没有得到广泛的支持,但它们是需要注意的。
    编辑 由于许多编译器不支持子模块,因此讨论其他选项可能会有所帮助。
    This page问了一个与此类似的问题,并有许多不错的链接。在关于 Google 群组的讨论中特别有用(尤其参见 this post)。总之,一种选择是:
  • 将所有库函数/子例程分组到一个文件中并单独分组(即不属于模块的一部分)。
  • 创建一个模块,该模块仅包含您想要向最终用户公开的那些子例程的接口(interface)。
  • 为最终用户提供编译后的模块和库。然后用户可以use他/她的程序中的模块并链接到库。

  • 这允许您“隐藏”您不想向最终用户公开的函数/子例程。
    从我链接到的帖子中提取:

    Some compilers generate a .mod (or whatever name the compiler gives to it) file and a library file. The .mod file has the symbols; the library file contains the executable code included in the module. When this is the case, you must distribute both files to your end users.

    Also, some compilers (in particular f95) put the symbols and the executable code into a single .mod file. In this case, you only need to provide the .mod file to your end users.


    (最终!)编辑有一个 useful page在 Fedora 维基上:

    Ideally, portable Fortran libraries would avoid the use of modules. The good news is that a Sub-module specification has been defined which will allow the interface specification part of a module to be separate from the procedure source code. On[c]e this is implemented in Fortran compilers, it should be utilized by all packaged libraries.

    关于fortran - 如何为 Fortran 95+ 模块库提供显式接口(interface),并隐藏实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10834402/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com