我可以使用 gcc 分别使用 g++ 或 gfortran 在 C 和 C++ 之间或 C 和 Fortran 之间进行调用.但是,如果我尝试在 C++ 和 Fortran 之间进行过程调用,则在使用 g++ 或 gfortran 进行编译时会出错,因为两者都不知道对方所需的库.
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.
如何链接使用 C++ 和 Fortran 编写的源代码的项目?
How can I link a project that uses source code written in both C++ and 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++ 链接:
I try linking with 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.
使用 gfortran:
And with 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++ 库的二进制文件链接在一起?
How can I link binaries using the gfortran and g++ libraries together?
您正在寻找g++ main.o print_hi.o -o main -lgfortran
在标准 Fortran 库中链接.
You're looking for
g++ main.o print_hi.o -o main -lgfortran
to link in the standard Fortran libraries.
你也可以通过传递-lstdc++
来使用gfortran
.
You can also use gfortran
by passing -lstdc++
.
这篇关于使用 gcc 链接 Fortran 和 C++ 二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!