Linking Fortran and C Binaries with GCC
To connect C and Fortran code using gcc, certain steps must be followed.
Suppose you have the following code:
// print_hi.f90 subroutine print_hi() bind(C) implicit none write(*,*) "Hello from Fortran." end subroutine print_hi // main.cpp #include <iostream> extern "C" void print_hi(void); using namespace std; int main() { print_hi(); cout << "Hello from C++" << endl; return 0; }
After compiling the individual object files using
gfortran -c print_hi.f90 -o print_hi.o g++ -c main.cpp -o main.o
To link these binaries together, you need to include the appropriate libraries. When using g , you should add the Fortran library using:
g++ main.o print_hi.o -o main -lgfortran
This includes the necessary library for Fortran functions.
Alternatively, if you're using gfortran, you can include the C library:
gfortran main.o print_hi.o -o main -lstdc++
Including these libraries ensures proper resolution of symbols and allows smooth execution of the linked binary.
The above is the detailed content of How to Link Fortran and C Binaries Together Using GCC?. For more information, please follow other related articles on the PHP Chinese website!