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

时光毁灭记忆、已成空白 提交于 2019-11-29 02:34:28

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.

Bálint Aradi

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!