使用gcc链接fortran和c ++二进制文件 [英] Linking fortran and c++ binaries using gcc

查看:346
本文介绍了使用gcc链接fortran和c ++二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用gcc分别通过g ++或gfortran在c和c ++之间或c和fortran之间进行调用。但是如果我尝试在c ++和fortran之间进行过程调用,则在使用g ++或gfortran编译时会遇到错误,因为它们不知道其他所需的库。如何链接使用在c ++和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

我尝试与g ++连接:

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.

与gfortran:

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

如何使用gfortran和g ++库将二进制文件链接在一起?

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

推荐答案

您正在寻找
g ++ main.o print_hi.o -o main -lgfortran 链接到标准Fortran库。

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

这篇关于使用gcc链接fortran和c ++二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆