gpt4 book ai didi

c - 混合编程发布失败但调试成功

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:27 25 4
gpt4 key购买 nike

在我的编译器中,名为“func”的函数在用 fortran 编译后将重命名为 _FUNC@*。如果 c 代码使用 _stdcall 调用约定,则函数名称,例如Ab,将重命名为_Ab@* 编译后。所以这可以导致fortran和c之间混合编程的简洁方法。以下是我的代码。source1.f90

program main
implicit none
call subprint()
read(*,*)
endprogram

代码.c

#include <stdio.h>
#ifdef _cplusplus
extern "C" {
#endif
void _stdcall SUBPRINT()
{printf("hello the world\n");}
#ifdef _cplusplus
}

我的平台是win 7,用的是vs2010。编译器是visual c++。 ccode.c 将生成一个 .lib,fortran 项目将使用它。这将在 Debug模式下成功运行。但是当我将项目更改为 Release模式时,会出现错误。错误是Source1.f90中的main函数找不到_SUBPRINT。请注意,我已经在 Release模式下生成了 .lib 并将其添加到 fortran 项目中。

混合编程的另一种方法是使用 _cdecl 调用约定。以下代码将在调试和 Release模式下成功运行。

module abc
interface
subroutine subprint()
!dec$ attributes C,alias:'_subprint'::subprint
end subroutine
end interface
end module

program main
use abc
implicit none
call subprint()
read(*,*)
endprogram

这是 C 代码。默认调用约定只是 _cdecl。

#ifdef _cplusplus
extern "C" {
#endif
void subprint()
{printf("hello the world\n");}
#ifdef _cplusplus
}
#endif

为什么会这样?我将所有这些代码放在同一个解决方案中。所以配置是一样的。

最佳答案

首先,请注意您的 C 函数是 SUBPRINT 而不是 subprint,即使在 C 中也很重要。

其次,你应该使用__cplusplus,而不是_cplusplus

第三,只使用现代 Fortran 来实现与 C 的互操作性:

抄送:

#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
void subprint(){
printf("hello the world\n");
}
#ifdef __cplusplus
}
#endif

f.f90:

program main
implicit none

interface
subroutine subprint() bind(C,name="subprint")
end subroutine
end interface

call subprint()
read(*,*)
endprogram

gfortran c.cc f.f90

./a.out
hello the world

关于c - 混合编程发布失败但调试成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17105125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com