简体   繁体   English

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

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

I can use gcc to make calls between C and C++ or between C and Fortran by using g++ or gfortran, respectively.我可以使用 gcc 分别使用 g++ 或 gfortran 在 C 和 C++ 之间或 C 和 Fortran 之间进行调用。 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.但是,如果我尝试在 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++ 库的二进制文件链接在一起?

You're looking for g++ main.o print_hi.o -o main -lgfortran to link in the standard Fortran libraries.您正在寻找g++ main.o print_hi.o -o main -lgfortran以链接到标准 Fortran 库中。

You can also use gfortran by passing -lstdc++ .您还可以通过传递-lstdc++来使用gfortran

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

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