Calling C++ function from Fortran in Visual Studio 2010

可紊 提交于 2020-06-23 14:13:53

问题


I want to call a C++ function from Fortran. To do that, I make a FORTRAN project in Visual Studio 2010. After that I add a Cpp project to that FORTRAN project. The following errors occur when I want to build the program:

Error 1: unresolved external symbol print_C referenced in function MAIN_main.obj    
Error 2:    1 unresolved externals

Following are the Fortran program and C++ function.

Fortran program:

program main

  use iso_c_binding, only : C_CHAR, C_NULL_CHAR
  implicit none

  interface
    subroutine print_c ( string ) bind ( C, name = "print_C" )
      use iso_c_binding, only : C_CHAR
      character ( kind = C_CHAR ) :: string ( * )
    end subroutine print_c
  end interface

  call print_C ( C_CHAR_"Hello World!" // C_NULL_CHAR )
end

C++ function:

# include <stdlib.h>
# include <stdio.h>

void print_C ( char *text )

{
  printf ( "%s\n", text );

  return;
}

Thanks a lot in advance.


回答1:


Your problem is that since you compile with a C++ compiler, print_C is not a C function, but a C++ function. Since the Fortran code tries to call a C function, it cannot find the C++ function.

The solution to your problem therefore is

  • either compile with a C compiler, so you get actual C code,
  • or tell the C++ compiler that you actually want to declare a C function.

The latter is done with extern "C", like this:

extern "C" void print_C(char *text)
{
  printf("%s\n", text);
}

If you want to be able to compile your code both as C and as C++, you can use

#ifdef __cplusplus
extern "C"
#endif
void print_C(char *text)
{
  printf("%s\n", text);
}

The symbol __cplusplus is defined for C++, but not for C, so your code will work in both (of course only as long as the rest of your code also remains in that subset).



来源:https://stackoverflow.com/questions/25348868/calling-c-function-from-fortran-in-visual-studio-2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!