使用VS Code Run Task编译运行C程序时遇致命错误求助
VS Code Run Task合并编译运行C程序报错解决
问题描述
未使用Code Runner扩展,尝试通过VS Code的Run Task功能编译并运行C程序。单独编译后手动运行正常,但将编译与运行合并为同一任务时,出现以下错误:
cc1.exe: fatal error: world\hello_world.c: No such file or directory
原tasks.json代码如下:
{ "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\gcc.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: C:\\msys64\\mingw64\\bin\\gcc.exe" }, { "type": "shell", "label": "Run C Program", "command": "C:\\msys64\\mingw64\\bin\\gcc.exe -fdiagnostics-color=always -g ${file} ${fileDirname}\\${fileBasenameNoExtension}.exe s-and${fileDirname}\\${fileBasenameNoExtension}.exe", "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "detail": "compiler: C:\\msys64\\mingw64\\bin\\gcc.exe" } ] }
错误原因
你写的"Run C Program"任务的command完全错误:把编译命令和运行命令混在一起,还出现了无意义的s-and字符串。gcc是编译器,只能用来编译源码生成可执行文件,不能用它来运行exe,这种错误的命令格式导致路径解析出错。
解决方案
提供两种可行的修正方式:
方式1:用Shell命令串联编译和运行
直接修改任务的command,用&&连接编译命令和运行命令(只有编译成功才会执行运行步骤):
{ "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\gcc.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: C:\\msys64\\mingw64\\bin\\gcc.exe" }, { "type": "shell", "label": "Build and Run C Program", "command": "C:\\msys64\\mingw64\\bin\\gcc.exe -fdiagnostics-color=always -g ${file} -o ${fileDirname}\\${fileBasenameNoExtension}.exe && ${fileDirname}\\${fileBasenameNoExtension}.exe", "options": { "cwd": "${fileDirname}" }, "problemMatcher": [] } ] }
方式2:利用任务依赖(更规范)
保留原有的独立编译任务,新建一个运行任务,通过dependsOn指定先执行编译任务,再运行生成的可执行文件:
{ "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: gcc.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\gcc.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: C:\\msys64\\mingw64\\bin\\gcc.exe" }, { "type": "shell", "label": "Build and Run C Program", "command": "${fileDirname}\\${fileBasenameNoExtension}.exe", "options": { "cwd": "${fileDirname}" }, "problemMatcher": [], "dependsOn": "C/C++: gcc.exe build active file", "detail": "先编译再运行C程序" } ] }
说明
- 方式1适合快速实现,一步完成编译运行;
- 方式2更符合VS Code任务的设计逻辑,编译和运行职责分离,也方便单独调用编译任务。
内容的提问来源于stack exchange,提问作者Nishu Patel
相关产品推荐
相关产品推荐

