如何在VS Code中运行C/C++程序?是否支持保存自动编译运行?
Auto-Compile & Run C/C++ in VS Code on Save (Like Live Server)
Absolutely! You can set up auto-compile and auto-run for C/C++ in VS Code just like how Live Server refreshes HTML pages on save. Let me walk you through the most practical, user-friendly methods to get this working:
1. Use a Dedicated Extension (Quickest Setup)
These extensions are built to handle C/C++ execution with minimal configuration:
Code Runner: A popular all-in-one extension that supports auto-run on save.
- Install Code Runner from the VS Code Marketplace.
- Open your settings (
Ctrl+,on Windows/Linux,Cmd+,on Mac), search for "Code Runner: Run On Save" and check the box. - Ensure your compiler (GCC, Clang, or MSVC) is installed and added to your system PATH—Code Runner will detect it automatically.
C/C++ Compile Run: An extension made specifically for C/C++ workflows.
- Install the extension from the marketplace.
- Navigate to its settings, find "Auto Run On Save" and enable it.
- You can tweak compile flags (like adding
-Wallfor warnings) in the extension settings if you want to customize the build process.
2. Custom Setup with Tasks + File Watcher (For Full Control)
If you prefer avoiding extensions and want full control over the compile/run process, use VS Code's built-in tasks paired with a file watcher:
- Open your C/C++ project folder in VS Code.
- Create a
.vscode/tasks.jsonfile (if it doesn’t exist) and paste this configuration (adjust the compiler command to match your setup—replacegccwithclangorclfor MSVC if needed):
{ "version": "2.0.0", "tasks": [ { "label": "Compile & Run C/C++", "type": "shell", "command": "gcc ${file} -o ${fileDirname}/${fileBasenameNoExtension} && ${fileDirname}/${fileBasenameNoExtension}", "args": [], "group": { "kind": "build", "isDefault": true }, "problemMatcher": ["$gcc"], "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" } } ] }
- Install the File Watcher extension. Configure it to trigger your task on save:
- Open File Watcher settings, add a new watcher.
- Set "Files to Watch" to
**/*.cand**/*.cpp(covers both C and C++ files). - Set "Command" to
workbench.action.tasks.runTaskand "Arguments" to"Compile & Run C/C++".
Important Notes
- Make sure your compiler (GCC, Clang, MSVC) is properly installed and accessible via your system’s PATH. For Windows, you might need to use MinGW-W64 or the MSVC Build Tools.
- For multi-file projects, adjust the
commandintasks.jsonto include all source files (e.g.,gcc file1.c file2.c -o outputinstead of${file}).
内容的提问来源于stack exchange,提问作者Amit kumar
相关产品推荐
相关产品推荐

