在C,C++和Fortran中混合代码

Joe*_*itt 3 c c++ gcc interop fortran

我一直在玩C,C++和Fortran中的混合代码.我有一个简单的测试涉及C++(cppprogram.C)中的主程序:

#include <iostream>
using namespace std;
extern "C" {
  void ffunction_(float *a, float *b);
}

extern "C" {
  void cfunction(float *a, float *b);
}

void cppfunction(float *a, float *b);

int main() {
  float a=1.0, b=2.0;

  cout << "Before running Fortran function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  ffunction_(&a,&b);

  cout << "After running Fortran function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  cout << "Before running C function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  cfunction(&a,&b);

  cout << "After running C function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  cout << "Before running C++ function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  cppfunction(&a,&b);

  cout << "After running C++ function:" << endl;
  cout << "a=" << a << endl;
  cout << "b=" << b << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

...在C,C++和Fortran中调用过程:

C(cfunction1.c)

void cfunction(float *a, float *b) {
  *a=7.0;
  *b=8.0;
}
Run Code Online (Sandbox Code Playgroud)

C++(cppfunction1.C)

extern "C" {
  void cppfunction(float *a, float *b);
}

void cppfunction(float *a, float *b) {
  *a=5.0;
  *b=6.0;
}
Run Code Online (Sandbox Code Playgroud)

Fortran(ffunction.f)

subroutine ffunction(a,b)
a=3.0
b=4.0
end
Run Code Online (Sandbox Code Playgroud)

以下是我用来制作目标文件并将它们链接在一起的命令:

g++ -c cppprogram.C
gcc -c cfunction1.c
g++ -c cppfunction1.C
gfortran -c ffunction.f
g++ -o cppprogram cppprogram.o cfunction1.o cppfunction1.o ffunction.o
Run Code Online (Sandbox Code Playgroud)

这是我的错误:

cppprogram.o: In function `main':
cppprogram.C:(.text+0x339): undefined reference to `cppfunction(float*, float*)'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我知道编译器内部有时会想要将下划线附加到文件名中,但我认为我已经处理过了.这可以通过nm命令确定.某处有一个小错误......有人看到了吗?提前谢谢了.

chm*_*ike 6

更新:

声明cppfunctionextern "C"cppfunction1.C,但cppprogram.C你不声明为extern "C".既然mainC++你不需要申报cppfunctionextern "C"cppfunction1.C,除非你希望能够从C或Fortran语言调用它.

取出extern "C"cppfunction1.C.

  • `cppfunction`*在`main`之前声明.我的猜测是它使用了错误的调用约定,因为缺少`extern"C"`.您关于使用标题的说明是有效的. (2认同)