对“_gfortran_cpu_time_4”的未定义引用

Undefined reference to `_gfortran_cpu_time_4'

我正在尝试从 Rust 调用 Fortran 函数,但出现此错误:

/src/timer.f:4: undefined reference to `_gfortran_cpu_time_4'

我在网上搜索过,但找不到任何解决办法。 Fortran 代码 是:

subroutine timer(ttime)
  double precision ttime
  temp = sngl(ttime)
  call cpu_time(temp)
  ttime = dble(temp) 

  return
end

Rust 绑定 是:

use libc::{c_double};

extern "C" {
    pub fn timer_(d: *mut c_double);
}

我不知道我做错了什么。

正如评论者所说,您需要link to libgfortran

具体来说,在 Rust 世界中,您应该使用(或创建)一个 *-sys package 来详细说明适当的 linking 步骤并公开基础 API。然后在此基础上构建更高级别的抽象。


但是,我似乎不需要做任何事情:

timer.f90

subroutine timer(ttime)
  double precision ttime
  temp = sngl(ttime)
  call cpu_time(temp)
  ttime = dble(temp) 

  return
end

Cargo.toml

[package]
name = "woah"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]

build = "build.rs"

[dependencies]
libc = "*"

build.rs

fn main() {
    println!("cargo:rustc-link-lib=dylib=timer");
    println!("cargo:rustc-link-search=native=/tmp/woah");
}

src/main.rs

extern crate libc;

use libc::{c_double};

extern "C" {
    pub fn timer_(d: *mut c_double);
}

fn main() {
    let mut value = 0.0;
    unsafe { timer_(&mut value); }
    println!("The value was: {}", value);
}

它是通过

组合在一起的
$ gfortran-4.2 -shared -o libtimer.dylib timer.f90
$ cargo run
The value was: 0.0037589999847114086

这似乎表明此共享库不需要 libgfortranit's being automatically included

如果您改为创建静态库(并通过 cargo:rustc-link-lib=dylib=timer 适当地 link):

$ gfortran-4.2 -c -o timer.o timer.f90
$ ar cr libtimer.a *.o
$ cargo run
note: Undefined symbols for architecture x86_64:
  "__gfortran_cpu_time_4", referenced from:
      _timer_ in libtimer.a(timer.o)

在这种情况下,添加gfortran允许代码编译:

println!("cargo:rustc-link-lib=dylib=gfortran");

免责声明:我以前从未编译过 Fortran,所以很可能我做了一些愚蠢的事情。