Fortran编程:VScode配置
1. VSCode下载安装
VSCode下载安装(链接:https://code.visualstudio.com/)特别简单,就如同普通软件安装到自己指定文件即可。
2. Fortran环境安装
通过Cygwin安装gfortran,可以参考博文Cygwin安装教程和Cygwin及Wget安装。博文VScode中配置使用fortran有更全面的介绍。
3. VSCode安装Fortran相关插件
四个插件:Fortran,Modern Fortran, Fortran IntelliSense, Code Runner, Fortran Breakpoint Support,其中Fortran Breakpoint Support插件是必须的,另一个插件是代码高亮的。还会有很多有趣插件,以后根据使用再进行添加。
4. 利用VSCode编写第一个Fortran程序
找个地方新建一个文件夹,文件结构如下:
└── hello
├── hello.f
└── .vscode
├── launch.json
└── tasks.json
在hello文件夹中新建一个.vscode的文件夹,注意文件夹前面的“点”,然后在.vscode文件夹中新建两个文件launch.json和tasks.json(源自:Guide_VSCode-fortran)。内容分别如下,
4.1 Windows系统
launch.json:
{
"version": "2.0.0",
"configurations": [
{
"name": "Debug Fortran & build",
"type": "cppdbg",
"request": "launch",
"targetArchitecture": "x86",
"program": "${workspaceRoot}\\${fileBasenameNoExtension}.exe",
"miDebuggerPath": "gdb.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"externalConsole": true,
"preLaunchTask": "build_gfortran"
}
]
}
type : 指定调试编译器
name : 左侧运行和调试窗口显示的配置名
program : Fortran生成的可执行文件绝对路径
preLaunchTask : 调试运行前执行的命令,命令标签build在tasks.json文件中配置
tasks.json:
{
"version": "2.0.0",
"_runner": "terminal",
"tasks":[
{
"label": "build_gfortran",
"type": "shell",
"windows": {
"command": "gfortran"
},
"linux": {
"command": "gfortran"
},
"osx": {
"command": "gfortran"
},
"args": [
"-g",
"${file}",
"-o",
"${workspaceRoot}\\${fileBasenameNoExtension}.exe"
]
}
],
}
label : 对应launch.json中preLaunchTask设置的标签
type : 此处使用shell类型
command : 调用终端时执行的命令,根据自己安装的是gfortran还是ifort进行选择
args : 执行command时传递的参数
-g : 启用调试
${fileDirname}/${fileBasename} : 单个for文件编译;多个for文件编译时,修改为*.f*
-o : 输出可执行文件
${workspaceFolder}/${fileBasenameNoExtension} : 输出可执行文件的名称,${fileBasenameNoExtension}表示使用被调试文件去除后缀的名称。(注意:此处可执行文件的名称需要与launch.json文件中program设置的参数相匹配)
4.2 Linux
launch.json:
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "cppdbg",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/${fileBasenameNoExtension}",
"args": [],
"cwd": "${workspaceFolder}",
"preLaunchTask": "build"
}
]
}
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "gfortran",
"args": [
"-g",
"${fileDirname}/${fileBasename}",
"-o",
"${workspaceFolder}/${fileBasenameNoExtension}"
]
}
]
}
在hello目录新建一个文件hello.f90,这个文件也可以在VSCode新建。
program HelloWorld
print *,'Hello,World!'
read(*,*)
end
运行,Run或者Ctrl+F5
Windows
Linux
5. 出现问题汇总
gfortran : 无法将“gfortran”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
解决方法:将gfortran.exe文件夹添加到系统环境变量,如:C:\cygwin64\bin
After fixing “fortls could not be spawned” ide-fortran still not working
Error spawning fortls: Please check that fortran-language-server is installed and in your path.
解决方法:
安装Python3,执行pip install fortran-language-server
参考:FORTRAN IntelliSense extension (path) - Visual Studio Code