Calling C++ function from Fortran in Visual Studio 2010

前端 未结 1 1514
醉酒成梦
醉酒成梦 2021-01-27 15:00

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 err

相关标签:
1条回答
  • 2021-01-27 15:47

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

    0 讨论(0)
提交回复
热议问题