Mixed C++ and Fortran Linking Issue

久未见 提交于 2019-12-05 11:21:11
milancurcic

There are few issues here that don't let names of the objects match. First, specify in the C++ code that the external functions have the C signature:

In test.cpp:

extern "C" int Add( int *, int * );
extern "C" int Multiply( int *, int * );

See In C++ source, what is the effect of extern "C"? for more details.

In your Fortran code, make the interface explicit by placing procedures in the module, and use iso_c_binding to let Fortran objects appear as valid C objects. Notice that we can explicitly specify the names of the objects that the C or C++ programs will see through the bind keyword:

test_f.f90:

module mymod
use iso_c_binding
implicit none

contains

integer(kind=c_int) function Add(a,b) bind(c,name='Add')
    integer(kind=c_int) :: a,b
    Add = a+b
end function

integer(kind=c_int) function Multiply(a,b) bind(c,name='Multiply')
    integer(kind=c_int) :: a,b
    Multiply = a*b
end function

endmodule mymod

Compile (don't mind me using the Intel suite, my g++ & gfortran are very old):

$ ifort -c test_f.f90 
$ icpc -c test.cpp 

Link:

$ icpc test_f.o test.o

Executing a.out should now work as expected.

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