title: Linking Fortran and C++ binaries using gcc
body: <p>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.</p>
  
  <p>How can I link a project that uses source code written in both C++ and Fortran?</p>
  
  <pre><code>$ cat print_hi.f90
  subroutine print_hi() bind(C)
    implicit none
    write(*,*) "Hello from Fortran."
  end subroutine print_hi
  
  $ cat main.cpp
  #include &lt;iostream&gt;
  
  extern "C" void print_hi(void);
  
  using namespace std;
  
  int main() {
    print_hi();
    cout &lt;&lt; "Hello from C++" &lt;&lt; endl;
    return 0;
  }
  $ gfortran -c print_hi.f90 -o print_hi.o
  $ g++ -c main.cpp -o main.o
  </code></pre>
  
  <p>I try linking with g++:</p>
  
  <pre><code>$ 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'
  </code></pre>
  
  <p>and further errors regarding undefined references.</p>
  
  <p>And with gfortran:</p>
  
  <pre><code>$ gfortran main.o print_hi.o -o main
  main.o: In function `main':
  main.cpp:(.text+0xf): undefined reference to `std::cout'
  </code></pre>
  
  <p>...and so forth.</p>
  
  <p>How can I link binaries using the gfortran and g++ libraries together?</p>