YS_Jin
YS_Jin

Reputation: 55

How to combine fortran project with C++ project?

I am working on a numerical project with C++, but it will use several fortran subroutines in another fortran project. The fortran project has head files and multiple subroutine files. The file dependency is shown in the figure below: enter image description here

I am wondering that how can I implement this interface in visual studio? Can I set up two projects, one is for fortran, it includes all fortran code, another is for Cpp, in the header file and class file I use extern "C" key word to declare the fortran subroutine?

Update1: The compiler for fotran is Intel Fortran, the compiler for C++ is msvc using MFC and the standard windows libraries.

Upvotes: 1

Views: 1291

Answers (1)

Steve Lionel
Steve Lionel

Reputation: 7267

Create an executable project (and VS Solution) for the C++ part. Now add to that solution a Fortran Static Library project and add your Fortran files to it.

Right click on the C++ project and select Build Dependencies > Project Dependencies. Check the box of the Fortran library project to make it a dependent of the C++ project. In older versions of VS, this is all you would need to have the library linked in, but MS removed that function for non-Microsoft compilers, so you have some additional steps:

  • Right click on the C++ project, select Linker > General. In Additional Library Directories, put in the path to where the Fortran .LIB will be built. Note that this is a per-configuration option, so repeat it for the Release configuration (make sure you specify the correct Debug or Release folder for the library).
  • In Linker > Input > Additional Dependencies, insert the name of your Fortran .LIB file. Separate it from other entries there with a semicolon. To save time, select Configuration > All Configurations in the upper-left dropdown before doing this step.
  • Now right-click on the Fortran project, select Fortran > Libraries. Make sure that Runtime Library is set to Debug Multithread DLL for the Debug configuration, and Multithread DLL for the Release configuration

This should be all you need to build. You will likely want to use the C interoperability features in your Fortran code, including adding BIND(C) to any routines called by the C++ code, with a NAME= specifier with the case-sensitive name C++ will use. Be aware that the Fortran VALUE attribute means pass-by-value only when the routine has BIND(C).

There is a worked C_Calls_Fortran example in the Intel Fortran samples bundle at https://software.intel.com/content/www/us/en/develop/download/776976.html (under compiler_f\MixedLanguage). If you need more help, ask in the Intel Fortran user forum at https://community.intel.com/t5/Intel-Fortran-Compiler/bd-p/fortran-compiler

Upvotes: 3

Related Questions