Home  >  Article  >  Backend Development  >  How to Link Fortran and C Binaries Together Using GCC?

How to Link Fortran and C Binaries Together Using GCC?

DDD
DDDOriginal
2024-10-26 21:31:03602browse

How to Link Fortran and C   Binaries Together Using GCC?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn