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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5663083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:37:49  来源:igfitidea点击:

Linking Fortran and C++ binaries using gcc

c++gccfortran

提问by sverre

I can use gcc to make calls between C and C++ or between C and Fortran by using g++ or gfortran, respectively. But if I try to make procedure calls between C++ and Fortran I get errors when compiling with either g++ or gfortran because neither knows about the other's required libraries.

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

How can I link a project that uses source code written in both C++ and Fortran?

如何链接使用 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

I try linking with g++:

我尝试与 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'

and further errors regarding undefined references.

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

And with gfortran:

并使用 gfortran:

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

...and so forth.

……等等。

How can I link binaries using the gfortran and g++ libraries together?

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

回答by Jonathan Dursi

You're looking for g++ main.o print_hi.o -o main -lgfortranto link in the standard Fortran libraries.

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

You can also use gfortranby passing -lstdc++.

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