编译C ++ / Fortran混合代码时出现问题

时间:2018-09-01 09:23:57

标签: c++ fortran language-interoperability

我正在编写C ++ / Fortran混合编程,其中从C ++主程序中调用Fortran子例程。

在文件c-call-f.cpp中:

#include <iostream>

extern "C"
{
    void for_sub_(int *, double *, double *, int *);
}

int main()
{
    int i = 1, ny = 3;
    double x = 3.14159;
    double y[] = {1.1, 2.2, 3.3};
    for_sub_(&i, &x, y, &ny);

    return 0;
}

f_sub.f90文件中:

subroutine FOR_SUB(i,x,y,ny)
use, intrinsic :: iso_c_binding
implicit none
integer(c_long) :: i, ny
real(c_double) :: x
real(c_double) :: y(ny)

print *, "y = ", y(1:ny)

end subroutine FOR_SUB

上面的代码受C / Fortran编程教程的启发,该教程位于: Fortran calling C functions

我想复制C ++ / Fortran的代码。我用

gfortran -c f_sub.f90
g++ -c c-call-f.cpp
g++ f_sub.o c-call-f.o

但是我说错了

Undefined symbols for architecture x86_64:
 "__gfortran_st_write", referenced from:
     _for_sub_ in f_sub.o
 "__gfortran_st_write_done", referenced from:
     _for_sub_ in f_sub.o
 "__gfortran_transfer_array_write", referenced from:
     _for_sub_ in f_sub.o
 "__gfortran_transfer_character_write", referenced from:
     _for_sub_ in f_sub.o
 "__gfortran_transfer_integer_write", referenced from:
     _for_sub_ in f_sub.o
 "__gfortran_transfer_real_write", referenced from:
     _for_sub_ in f_sub.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)`

是什么导致错误?我还尝试在最后的编译步骤中添加标志-lf-lfortran-lg2c,但是会出现另一个错误:

ld: library not found for [flag]
clang: error: linker command failed with exit code 1 (use -v to see invocation)

[flag]是上述三个中的任何一个。

顺便说一句,为什么我在网上发现有关C / Fortran互操作性的资源似乎如此不一致,在一个地方,我读到您需要在声明中的过程名称后加上bind(C),而在另一个地方例如上面给出的链接,则无需这样做。另一件事,我读到有人说您不需要在调用单元中的子例程名称后添加尾随下划线,而在其他地方则需要。令人困惑,其中哪个是错误的?

0 个答案:

没有答案
相关问题