how to call a Fortran90 function included in a module in c++ code?

前端 未结 2 1098
北海茫月
北海茫月 2020-12-15 12:59

I m including a fortran90 program that is not mine in my C++ project .

In the first stept I try to call the function by their name_() and i get the error \"undefin

相关标签:
2条回答
  • 2020-12-15 13:38

    First of all, on the Fortran side I strongly suggest to use the Fortran 2003 features of C-bindings, and especially the iso_c_binding module. You can see many examples for that on SO, among others this post. Then you get rid of the "how does my fortran compiler name my procedures" problem in a transparent and compiler independent way.

    The linking problem arrises as you are missing some libraries of your Fortran compiler I guess. You either can try to link your object file using the Fortran compiler, or find out which library is missing and link it manually. Some Fortran compiler have also options for creating a library with automatical linking of compiler related libraries.

    0 讨论(0)
  • 2020-12-15 13:39

    I am assuming you are using the g++, gfortran, mpif90 toolchain. If you have a module

    module rocker
    contains
    subroutine bye_baby
    ...
    end subroutine
    

    The external C declaration for it in C++ is

    extern "C"
    {
        //          ,-- 2 Leading underscores to start
        //          | ,-- then the module name
        //          | |     ,-- then _MOD_
        //          | |     |    ,-- then the subroutine name
        //          V V     V    V
        extern void __rocker_MOD_bye_baby();
    }
    

    You may also need to add attribute((stdcall)) after the extern. By default, C assumes cdecl which stacks the parameters differently.

    If you do not want the __rocker_MOD part, then the subroutine/function should not be declared in a module.

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