xmake文件和配置
在windows上搞fortran/c/c++混编一直没有什么太方便的解决方案,这点就不如linux下的工具链成熟了。现在我们有了mingw和xmake,实现混编就方便多了。
xmake是一个纯国产编译构建系统,关于xmake的介绍,可以见这里:
https://zhuanlan.zhihu.com/p/266523197
首先来看编译脚本的内容,这个其实可以用xmake来自动生成:
xmake create -l fortran -t console test
上述命令创建了一个名为test的控制台fortran程序。但其实如果将cpp文件添加进去,它也会识别并调用gcc编译器来编译。 这就是用mingw的好处,工具链比较统一。
编译配置的lua脚本如下:
xmake.lua
add_rules("mode.debug", "mode.release")
target("test")
set_kind("binary")
add_files("src/*.f90")
add_files("src/*.cpp")
xmake 需要指定编译器为gfortran
xmake config --toolchain=gfortran
另外要注意,采用mingw g++的时候,gfortran会在函数末尾加下划线,所以c函数如果要被fortran调用,也得加下划线。stackoverflow上给了如下一个宏用来方便写程序
#ifdef __GNUC__
#define FORT(func) func ## _
#else
#define FORT(func) __stdcall func ## _
#endif
#ifdef __cpluscplus
extern "C" {
#endif
__declspec(dllexport) int FORT(sayit)(char* c)
{
return printf("%s\n",c);
}
#ifdef __cpluscplus
来源: https://stackoverflow.com/questions/354182/calling-c-code-from-fortran
c++ 文件
#include <stdio.h>
extern "C" void fortran_say_hello_(); // defined in main.f90
// for gcc , a '_' is required for fortran code
extern "C" void foo_()
{
printf("this is from c++ foo()!\n");
fortran_say_hello_();
}
注意上面无论是导出给fortran用的函数, 还是声明从fortran中来的函数,都在末尾加了下划线。
fortran文件
main.f90
program hello
INTERFACE
SUBROUTINE foo
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_INT
IMPLICIT NONE
END SUBROUTINE foo
END INTERFACE
print *, "Hello World!"
call foo
end program hello
subroutine fortran_say_hello
print *, "Fortran says : Hello World!"
return
end subroutine