问题
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