簡體   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