This question already has an answer here:
About using Fortran function in C with iso_c_binding
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
我的解决方案中有两个项目:CPartFortranPartFortranPart取决于CPart,后者包含main函数。这是main.c的代码

#include <stdio.h>

extern int __stdcall FORTRAN_ADD(int *A, int *B);

int main()
{
    int a = 3;
    int b = 4;
    int c = FORTRAN_ADD(&a, &b);

    printf("%i\n", c);

    return 0;
}


这是我的fortran模块的代码

module FORTRAN_UTILS

implicit none

contains

integer*4 function fortran_add(a, b) result(c)
implicit none
integer*4, intent(in) :: a, b
c = a + b
end function fortran_add

end module FORTRAN_UTILS


在编译了fortran之后,我得到文件FortranPart.lib。在CPart项目依赖项中,我将其添加为外部库。当我尝试编译并运行CPart时,我得到以下信息

Error   LNK2019 unresolved external symbol _FORTRAN_ADD@8 referenced in function _main  CPart   c:\Users\sasha\documents\visual studio 2015\Projects\MSCourse\MSCourse\main.obj 1


附言
我需要主程序使用C而不是C ++。

最佳答案

更多的研究为我带来了这一页
https://software.intel.com/ru-ru/node/678422

我稍稍更改了代码,现在可以正常工作了。

subroutine fortran_add(a, b, r) bind(c)
    use, intrinsic :: iso_c_binding
    implicit none
    integer (c_int), value :: a, b
    integer (c_int), intent(out) :: r
    r = a + b
    end subroutine fortran_add


main.c

#include <stdio.h>

void fortran_add(int a, int b, int *r);

int main()
{
    int a = 3;
    int b = 4;
    int c;

    fortran_add(a, b, &c);

    printf("%i\n", c);

    scanf_s("");

    return 0;
}

09-11 16:04