Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking Fortran and C++ binaries using gcc

Tags:

c++

gcc

fortran

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.

How can I link a project that uses source code written in both C++ and Fortran?

$ cat print_hi.f90 subroutine print_hi() bind(C)   implicit none   write(*,*) "Hello from Fortran." end subroutine print_hi  $ cat main.cpp #include <iostream>  extern "C" void print_hi(void);  using namespace std;  int main() {   print_hi();   cout << "Hello from C++" << endl;   return 0; } $ gfortran -c print_hi.f90 -o print_hi.o $ g++ -c main.cpp -o main.o 

I try linking with g++:

$ 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' 

and further errors regarding undefined references.

And with gfortran:

$ gfortran main.o print_hi.o -o main main.o: In function `main': main.cpp:(.text+0xf): undefined reference to `std::cout' 

...and so forth.

How can I link binaries using the gfortran and g++ libraries together?

like image 814
sverre Avatar asked Apr 14 '11 12:04

sverre


People also ask

Can GCC compile Fortran?

GCC can compile programs written in any of these languages. The Ada, Fortran, Java and treelang compilers are described in separate manuals. "GCC" is a common shorthand term for the GNU Compiler Collection.

Can G ++ compile C?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.

Is G ++ and GCC the same?

“GCC” is a common shorthand term for the GNU Compiler Collection. This is both the most general name for the compiler, and the name used when the emphasis is on compiling C programs (as the abbreviation formerly stood for “GNU C Compiler”). When referring to C++ compilation, it is usual to call the compiler “G++”.

What is .O file in Fortran?

gfortran -o executable object1.o object2.o ... where the the executable will be named executable and the objectN.o are object files, which may have been created as above, or equally well by another compiler from sources in a different language. If -o executable is omitted, the executable will be named a.


1 Answers

You're looking for g++ main.o print_hi.o -o main -lgfortran to link in the standard Fortran libraries.

You can also use gfortran by passing -lstdc++.

like image 123
Jonathan Dursi Avatar answered Oct 11 '22 12:10

Jonathan Dursi