跨平台开发的核心是使用广泛支持的编译器,避免依赖特定平台的工具。Ubuntu上首选GNU Fortran(gfortran)——它是GCC的一部分,支持Fortran 95/2003/2008标准,且在Windows(通过MinGW-w64)、macOS(通过Homebrew)等平台均有对应版本,编译结果兼容性强。
安装gfortran:
sudo apt update
sudo apt install gfortran
验证安装:
gfortran --version # 应输出gfortran版本及目标平台(如x86_64-linux-gnu)
若需更严格的跨平台一致性,建议固定gfortran版本(如通过sudo apt install gfortran-12安装特定版本),避免因编译器升级导致代码行为变化。
不同操作系统(如Windows与Linux)的系统调用、文件路径分隔符、API存在差异,需通过条件编译指令隔离平台相关代码。Fortran中可使用#ifdef结合预定义宏(如__linux__、_WIN32)区分平台:
program cross_platform_demo
implicit none
#ifdef __linux__
print *, "Running on Linux"
! Linux-specific code (e.g.,使用/作为路径分隔符)
#elif _WIN32
print *, "Running on Windows"
! Windows-specific code (e.g.,使用\作为路径分隔符)
#else
print *, "Unknown platform"
#endif
end program cross_platform_demo
编译时无需额外参数,预处理器会自动处理条件代码,确保在不同平台编译时仅包含对应逻辑。
手动编写Makefile或Shell脚本易出错,建议使用跨平台构建工具自动化编译过程。推荐以下工具:
fpm.toml配置文件,即可通过fpm build编译、fpm run运行:wget https://github.com/fortran-lang/fpm/releases/download/v0.9.0/fpm-0.9.0-linux-x86_64.tar.gz
tar -xzf fpm-0.9.0-linux-x86_64.tar.gz
export PATH=$PATH:/path/to/fpm-0.9.0-linux-x86_64/bin
fpm init # 初始化项目
fpm build # 编译项目(生成跨平台可执行文件)
FindFortran模块查找gfortran,生成适用于不同平台的Makefile或Visual Studio项目:cmake_minimum_required(VERSION 3.10)
project(MyFortranProject)
enable_language(Fortran)
add_executable(my_program main.f90)
target_link_libraries(my_program PRIVATE m) # 链接数学库
构建时,只需在对应平台运行cmake和make即可。科学计算或图形界面开发需依赖外部库,应选择跨平台库并正确链接。常见跨平台库及用法:
apt安装后直接链接:sudo apt install libblas-dev liblapack-dev
gfortran my_program.f90 -lblas -llapack -o my_program
apt安装Ubuntu版本后链接:sudo apt install intel-mkl-2020.4-088
gfortran my_program.f90 -L/usr/lib/x86_64-linux-gnu -lmkl_rt -lpthread -lm -ldl -o my_program
apt安装后编译:sudo apt install libgtk-3-dev
gfortran hello-world.f90 `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0` -o hello-world
确保库文件在目标平台(如Windows)也存在,或使用静态链接(如-static参数)避免动态库依赖问题。跨平台开发需在目标平台上充分测试,确保代码行为一致:
gdb调试(gfortran -g my_program.f90 -o my_program,再运行gdb ./my_program),检查逻辑错误。mingw-w64(sudo apt install mingw-w64),使用x86_64-w64-mingw32-gfortran编译生成Windows可执行文件(.exe),在Windows上运行测试。选择支持多平台的IDE,简化代码编写、调试和项目管理:
Fortran插件(如Modern Fortran)支持语法高亮、代码补全、调试(需配置launch.json)。跨平台支持好,适合轻量级开发。通过以上步骤,可在Ubuntu上搭建跨平台兼容的Fortran开发环境,确保代码在Windows、macOS等其他平台上顺利编译和运行。关键是选择通用的工具链(如gfortran)、处理平台差异(如条件编译)、使用跨平台库和构建工具,并在目标平台上充分测试。