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

How to Link Fortran and C Binaries Together Using GCC?

DDD
Release: 2024-10-26 21:31:03
Original
670 people have browsed it

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;
}
Copy after login

After compiling the individual object files using

gfortran -c print_hi.f90 -o print_hi.o
g++ -c main.cpp -o main.o
Copy after login

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
Copy after login

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++
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template