Fortran makes it quite easy to add subroutines/functions from other languages like C/C++. Below is a short example on how to rewrite the Hello world example in C++ then run it from a Fortran script. See documentation at the bottom of the page to learn how to do it the other way around, implementing Fortran functions in C++ code

First we write the function hello() in C++. Create a .cpp file and name it "sub" (short for subroutine) . Below is  an example of the code to put in sub.cpp. Feel free to modify the function declaration.

#include <iostream>

extern "C" void hello(); #This line is needed for the main function to recognize the hello() function 

void hello()
{
  std::cout << "Hello World" << std::endl; 
  return;
}


Now we may create the main file. Start by creating a blank f.90 file and name it "main" Add the following code

program main
  implicit none
  ! Declare C/C++ function.
  interface
    subroutine hello() bind (c)
    end subroutine
  end interface
  ! Call C/C++ function.
  call hello()
end program


Now try running the project. Try changing the hello() function and play around with the interface in main. To check your understanding . 


For further reading on how to implement C++ in Fortran (and vice versa) Check this

pdf from Lawrence Livermore National Laboratory



Page content



The Bibtex display table macro can not be displayed.

Please ensure that each Bibtex reference is properly formed. Also note that only the following Bibtex entry types are supported: article, book, conference, inbook, inproceedings, mastersthesis, misc, phdthesis, proceedings, techreport.

  • No labels