如何在没有安装 gfortran 的情况下将 fortran 代码编译为 运行

How to compile fortran code to run without gfortran installed

我已经下载了 Bellhop,它是一个用 Fortran 编写的水下声学模拟器。可以在 Makefile 中找到 here

问题 1:我想知道是否可以编译 Fortran 代码,包括所需的一切,所以没有安装 gfortran 的用户可以 运行 它。

我已阅读 here 以下内容:

static linking This section does not apply to Windows users, except for Cygwin users with gcc4-4.3.2-2 or later. gfortran is composed of two main parts: the compiler, which creates the executable program from your code, and the library, which is used when you run your program afterwards. That explains why, if gfortran is installed in a non-standard directory, it may compile your code fine but the executable may fail with an error message like library not found. One way to avoid this (more ideas can be found on the binaries page) is to use the so-called "static linking", available with option -static gfortran then put the library code inside the program created, thus enabling it to run without the library present (like, on a computer where gfortran is not installed). Complete example is:

gfortran -static myfile.f -o program.exe

读到这里,我想可以做我想做的事情,但我对 fortran 和 makefile 不是很熟悉。我不明白这个:

put the library code inside the program created

问题2:如何将库代码放入程序中?我在哪里可以找到图书馆? "inside the program" 是什么意思?

我正在 运行宁 OSX 10.9.4 和 gfortran

我觉得加粗部分的意思其实是

gfortran then puts the library code inside the program created

也就是说使用-static应该就够了,没有额外的步骤。请注意,您将需要 link 使用的所有库的静态版本。

选项的当前版本是-static-libgfortran。这意味着 gfortran 的 Fortran 特定库将包含在可执行文件中。这些库是自动找到的,用于良好安装 gfortran。这应该会生成一个可执行文件,即使该计算机没有安装 gfortran,也应该在其他具有相同 OS 的计算机上 运行。此选项可能不会静态 link 所有库,因此存在一些风险,即您计算机上使用的某些其他共享库在另一台计算机上不可用。

我解决了使用静态库使用 gfortran 编译 Fortran 代码的问题。 作为@M.S.B。说,使用 static-libgfortran 在 MacOS 下对我有用。

如果有人在链接 libquadmath.0.dylb 库时遇到问题,请删除 libquadmath.0.dyliblibquadmath.dylib 来自 /usr/local/gfortran/lib/

这就成功了。可以找到更多信息 here

我知道这是非常古老的跟踪器,但也许有人会对有效的解决方案感兴趣。

假设我们有代码:

! fort_sample.f90
program main
  write (*,*) 'Hello'
  stop
end

首先,编译这些东西:

gfortran -c -o fort_sample.o fort_sample.f90

然后,link东西

ld -o ./fort_sample -no_compact_unwind \
-arch x86_64 -macosx_version_min 10.12.0 \
-lSystem \
/usr/local/gfortran/lib/libgfortran.a \
/usr/local/gfortran/lib/libquadmath.a \
/usr/local/gfortran/lib/gcc/x86_64-apple-darwin16/6.3.0/libgcc.a \
fort_sample.o

你可以执行它

./fort_sample
 Hello

您会注意到 quadmath 不再存在

> otool -L fort_sample
fort_sample:
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.51.1)

我想这就是您首先要找的东西。没有删除动态库,没有符号 links 等