问题
I am trying to call the c++ function from Fortran main program. to do that I followed the bellow steps in visual Studio 2010: To create a C++ static library project
- On the menu bar, choose File, New, Project.
- In the left pane of the New Project dialog box, expand Installed, Templates, Visual C++, and then select Win32.
- In the center pane, select Win32 Console Application.
- Specify a name for the project—for example, MathFuncsLib—in the Name box. Specify a name for the solution—for example, StaticLibrary—in theSolution Name box. Choose the OK button.
- On the Overview page of the Win32 Application Wizard dialog box, choose the Next button.
- On the Application Settings page, under Application type, select Static library.
- On the Application Settings page, under Additional options, clear the Precompiled header check box.
- Choose the Finish button to create the project.
To create a executable Fortran project
- On the menu bar, choose File, New, Project.
- In the left pane of the New Project dialog box, expand Installed, Templates, Intel(R) Visual Fortran , and then select Console Application.
- In the center pane, select Empty Project.
- Specify a name for the project and then Specify a name for the solution. In the solution box select the "Add to solution". Choose the OK button.
In addition I do some setting in Visual studio as below:
- Right-click the executable Fortran project and select Dependencies to set the executable project as dependent on the static library project.
- Right-click on the executable project and select Set as Startup Project so that you can build it and debug. I have the below Fortran main 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>
extern "C" void print_C (char *text)
{
printf("%s\n", text);
}
When I build the program I will confront to the following errors:
Error 1: error LNK2019: unresolved external symbol _print_C referenced in function _MAIN__ Fortranmain.obj
Error 2: fatal error LNK1120: 1 unresolved externals Debug\Fortranmain.exe
Could anyone help me? Any suggestion would be highly appreciate.
回答1:
You need to link C++ library to Fortran executable. Dependencies are specifying the build order.
- Right-click the executable Fortran project and select Properties
- Add directory containing build C++ library to Configuration Properties -> Linker - General -> Additional Library Directories (This step is maybe not needed)
- Add C++ library .lib file to Configuration Properties -> Linker -> Input -> Additional Dependancies
来源:https://stackoverflow.com/questions/25379086/how-to-mix-fortran-and-c-in-visual-studio-2010