我可以使用 gcc 在 C 和 C++ 之间或 C 和 Fortran 之间分别使用 g++ 或 gfortran 进行调用。但是,如果我尝试在 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'
以及关于 undefined reference 的更多错误。
并且使用 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
。
关于c++ - 使用 gcc 链接 Fortran 和 C++ 二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663083/