Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

Linking Fortran and C++ binaries using gcc

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?

question from:https://stackoverflow.com/questions/5663083/linking-fortran-and-c-binaries-using-gcc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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++.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...