繁体   English   中英

使用 gcc 链接 Fortran 和 C++ 二进制文件

[英]Linking Fortran and C++ binaries using gcc

我可以使用 gcc 分别使用 g++ 或 gfortran 在 C 和 C++ 之间或 C 和 Fortran 之间进行调用。 但是,如果我尝试在 C++ 和 Fortran 之间进行过程调用,则在使用 g++ 或 gfortran 进行编译时会出错,因为两者都不知道对方所需的库。

如何链接使用 C++ 和 Fortran 编写的源代码的项目?

$ cat print_hi.f90
subroutine print_hi() bind(C)
  implicit none
  write(*,*) "Hello from Fortran."
end subroutine print_hi

$ cat main.cpp
#include <iostream>

extern "C" void print_hi(void);

using namespace std;

int main() {
  print_hi();
  cout << "Hello from C++" << endl;
  return 0;
}
$ gfortran -c print_hi.f90 -o print_hi.o
$ g++ -c main.cpp -o main.o

我尝试与 g++ 链接:

$ g++ main.o print_hi.o -o main
print_hi.o: In function `print_hi':
print_hi.f90:(.text+0x3f): undefined reference to `_gfortran_st_write'

以及关于未定义引用的进一步错误。

并使用 gfortran:

$ gfortran main.o print_hi.o -o main
main.o: In function `main':
main.cpp:(.text+0xf): undefined reference to `std::cout'

……等等。

如何将使用 gfortran 和 g++ 库的二进制文件链接在一起?

您正在寻找g++ main.o print_hi.o -o main -lgfortran以链接到标准 Fortran 库中。

您还可以通过传递-lstdc++来使用gfortran

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM