简体   繁体   中英

Calling C++ function from Fortran in Visual Studio 2010

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM