modern fortran扩展需gfortran和python3均在path中,fortls必须手动pip安装并显式配置路径,否则语法高亮、跳转定义等功能失效;调试须用含-g的编译命令及launch.json配置gdb。

gfortran 装好了、Modern Fortran 扩展也装了,但代码没高亮、fortls 启动失败、Ctrl+Click 跳不到模块定义——这不是环境没配好,是关键依赖链断在了 Python 或路径上。
确认 gfortran 和 python3 都在系统 PATH 里
VSCode 的 Fortran 插件不是独立运行的,它靠外部工具协同工作:gfortran 做语法检查和编译,python3 运行 fortls(语言服务器),两者缺一不可。
- 终端执行
gfortran --version和python3 --version,必须都能输出版本号;任一失败,插件就卡在“Language Server Starting…” - Windows 用户尤其注意:MinGW-w64 安装后,
gfortran.exe所在目录(如C:mingw64in)必须手动加进系统环境变量PATH,否则 VSCode 终端能识别,GUI 启动的 VSCode 却找不到 - macOS 用户若用 Homebrew 安装了多个 Python 版本(如 pyenv),确保
python3指向的是能运行pip install fortls的那个版本,别用/usr/bin/python3(系统自带的常不带 pip)
fortls 必须用 pip install fortls 安装,不能只靠扩展自动安装
Modern Fortran 扩展声称“自动安装 fortls”,但实测在多数系统(尤其是 Linux/macOS 非 root 环境或 Windows WSL)下会静默失败,且不报错。
- 务必在终端手动执行:
pip install fortls;如果提示权限错误,改用pip install --user fortls - 安装后验证:
fortls --version应输出类似fortls 2.4.1;若报 “command not found”,说明pip安装的可执行文件路径没进PATH(Linux/macOS 查~/.local/bin,Windows 查%APPDATA%PythonPython3xScripts) - VSCode 设置中显式指定路径更可靠:
"fortran.fortls.path": "/home/you/.local/bin/fortls"(Linux/macOS)或"fortran.fortls.path": "C:\Users\You\AppData\Roaming\Python\Python311\Scripts\fortls.exe"(Windows)
调试前先配好 launch.json,别指望 Code Runner 编译带调试信息
Code Runner 默认用 gfortran -o $fileNameWithoutExt $fileName 编译,不加 -g,GDB 就看不到变量名和源码行——断点设了也停不住。
- 在项目根目录建
.vscode/launch.json,用cppdbg类型配置 GDB:
{
"version": "0.2.0",
"configurations": [
{
"name": "Fortran Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/main",
"miDebuggerPath": "gdb",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{ "description": "Enable pretty-printing", "text": "-enable-pretty-printing", "ignoreFailures": true }
],
"preLaunchTask": "build"
}
]
}
tasks.json,确保编译命令含 -g -O0(调试优先):{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "gfortran",
"args": [
"-g", "-O0", "-Wall", "-fcheck=all",
"-c", "${file}",
"-o", "${fileDirname}/build/${fileBasenameNoExtension}.o"
],
"group": "build",
"problemMatcher": ["$gcc"]
}
]
}
Code Runner 适合快速跑单文件脚本,但只要涉及模块调用、数组调试、数值精度追踪,就必须切到正式调试流程多模块项目里,include 和 use 的路径容易被忽略
VSCode 的 fortls 默认只扫描当前文件和同级目录,use my_module 报 “cannot find module” 不一定是拼写错,很可能是模块文件不在搜索路径里。
- 在
.vscode/settings.json中显式声明模块路径:"fortran.fortls.includePaths": ["${workspaceFolder}/src/modules", "${workspaceFolder}/lib"] - 避免用 C 风格的
#include "xxx.h";Fortran 的include 'file.inc'是文本替换,路径必须相对于包含它的源文件,不是工作区根目录 - 模块文件(
.f90)必须已编译过(或至少被fortls解析过),use语句才能跳转;刚新建的my_module.f90如果没保存、没触发解析,use my_module会灰显











