混合 C、C++ 和 Fortran 中的代码
Mixing code in C, C++, and 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;
}
。C、C++ 和 Fortran 中的调用过程:
C ( cfunction1.c
)
void cfunction(float *a, float *b) {
*a=7.0;
*b=8.0;
}
C++ ( cppfunction1.C
)
extern "C" {
void cppfunction(float *a, float *b);
}
void cppfunction(float *a, float *b) {
*a=5.0;
*b=6.0;
}
福特兰 ( ffunction.f
)
subroutine ffunction(a,b)
a=3.0
b=4.0
end
以下是我用来制作目标文件并将它们链接在一起的命令:
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
这是我的错误:
cppprogram.o: In function `main':
cppprogram.C:(.text+0x339): undefined reference to `cppfunction(float*, float*)'
collect2: error: ld returned 1 exit status
我知道编译器有时希望在文件名后附加下划线,但我认为我已经处理好了。 这可以通过nm
命令确定。 某处有一个小错误...有人看到吗? 提前非常感谢。
更新:
你在cppfunction1.C
中将cppfunction
声明为extern "C"
,但在cppprogram.C
中你没有将其声明为extern "C"
。由于main
是C++
因此,除非您希望能够从 C 或 Fortran 调用它,否则无需在 cppfunction1.C
中将cppfunction
声明为 extern "C"
。
从cppfunction1.C
中删除extern "C"
。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 重新编译我们的FORTRAN代码并在C++中使用后,我们的system()或C_str()命令无法正常工作
- CPP -D 选项,用于预处理 Fortran 代码
- complex_Bessel_function库的编译——与Fortran代码的链接——mex文件
- 旧版本的Fortran做循环Manova代码
- 在C++和Fortran代码之间传递复数数组
- 当C代码调用Fortran子程序时,子程序顶部会出现分段错误
- 从QTCreator中调用QT的Fortran代码
- 将 MPI 消息从 C++ 代码发送到 Fortran 90 代码
- 混合 C、C++ 和 Fortran 中的代码
- 集成 Fortran 和 C++ 代码的查询
- Cmake配置文件,用于从FORTRAN代码调用的C++函数中调用C++代码
- 使用Visual Studio 2013和Intel Fortran编译c++ /C混合代码
- FORTRAN代码调用c代码时发生错误
- 从FORTRAN代码调用的c++函数调用c++函数
- 用内存中的Fortran数据调用C代码
- 我怎样才能使这个简单的fortran 90代码更快
- 使用C++代码从FORTRAN DLL调用函数
- Fortran 将字符*81 数组传递给 C/C++ 代码