【发布时间】:2013-02-27 16:33:43
【问题描述】:
我必须从我的 fortran 程序中调用一个 C++ 函数。我正在使用 Visual Studio 2010。我阅读了本书 http://www.amazon.com/Guide-Fortran-Programming-Walter-Brainerd/dp/1848825420 中有关 2003 ISO C 绑定的相关章节。我试图编译并运行第 219 页的简单示例(我在下面复制了它),但它显示“错误 LNK2019:未解析的外部符号 _c 在函数 _MAIN__ 中引用”。这些是我遵循的步骤。
1)我用Fortran主程序和模块创建了一个Fortran项目,并将其设置为“启动项目”。
2)我创建了一个“静态库”类型的 C++ 项目。
3)我添加了 $(IFORT_COMPILERvv)\compiler\lib\ia32 ,正如此处http://software.intel.com/en-us/articles/configuring-visual-studio-for-mixed-language-applications 所解释的那样
当我编译时,我得到了那个错误。如果我评论 Call C 行,它会完美运行,所以它找不到 C 函数。有什么建议吗?提前致谢。以下是 C 和 Fortran 代码:
module type_def
use, intrinsic :: iso_c_binding
implicit none
private
type, public, bind(c) :: t_type
integer(kind=c_int) :: count
real(kind=c_float) :: data
end type t_type
end module type_def
program fortran_calls_c
use type_def
use, intrinsic :: iso_c_binding
implicit none
type(t_type) :: t
real(kind=c_float) :: x, y
integer(kind=c_int), dimension(0:1, 0:2) :: a
interface
subroutine c(tp, arr, a, b, m) bind(c)
import :: c_float, c_int, c_char, t_type
type(t_type) :: tp
integer(kind=c_int), dimension(0:1, 0:2) :: arr
real(kind=c_float) :: a, b
character(kind=c_char), dimension(*) :: m
end subroutine c
end interface
t = t_type(count=99, data=9.9)
x = 1.1
a = reshape([1, 2, 3, 4, 5, 6], shape(a))
call c(t, a, x, y, "doubling x" // c_null_char)
print *, x, y
print *, t
print *, a
end program fortran_calls_c
#include "stdafx.h"
//#include <iostream>
#include <fstream>
typedef struct {int amount; float value;} newtype;
void c(newtype *nt, int arr[3][2], float *a, float *b, char msg[])
{
printf (" %d %f\n", nt->amount, nt->value);
printf (" %d %d %d\n", arr[0][1], arr[1][0], arr[1][1]);
printf (" %s\n", msg);
*b = 2*(*a);
}
【问题讨论】:
-
您的
c++函数名称将被破坏。要停止此操作,请使用extern "c"。 -
谢谢,但我尝试用 extern "C" void c(....) 替换 C++ 代码中的行,但没有任何改变...
-
好吧,没有一个真正知道他们在做什么的人在这里插话......我前段时间玩过这个,从来没有在 Windows 上玩过,但是哦,好吧。现在我有一个模糊的记忆,编译器会在 Fortran 中的函数名末尾添加一个 _。但是在这种情况下,错误是
unresolved external symbol _c,所以它看起来像在 Windows 中它在前面。试试extern "c" void _c (newtype *nt, int arr[3][2], float *a, float *b, char msg[]){...}。 -
啊,我根本没有 Windows。我想建议切换到真正的操作系统,但不知何故我怀疑这不是一个有用的答案。阅读this。你是编译c++ 64位的吗?
-
伙计们,如果我充分理解了 2003 C 绑定已经解决了所有重命名问题。否则我们为什么要使用它?事实上,下面的答案是可行的,但你必须这样做并且为你添加的每个 C++ 项目这样做是很奇怪的。
标签: c++ visual-studio fortran fortran-iso-c-binding