环境与配置
IDE选择
遥想三年多前的大一上学期,上C语言程序设计的课,老师上课、同学们写作业基本都是用的Dev-C++,它页面简洁,操作简单,极具轻量化,是很多初学者使用的第一个代码编辑器。
但是如果作为开发工具,则效率太低,原因如下:
- 没有代码补全
- 调试工具难用
- 界面不美观(个人感觉)
因此,建议使用VS Code。VsCode是好评如潮的代码编辑器,受到很大一部分人追捧,但是在VsCode上配置C/C++环境还是有些难度的,自己摸索的初学者想在VsCode上跑通HelloWorld可能都得花一两天。
在VsCode上配置C/C++编程运行环境
在VsCode上配置C/C++编程运行环境主要分三步走:
- 下载mingw并配置环境变量
- 下载并安装VsCode
- VsCode中配置C/C++ 运行环境
下载mingw并配置环境变量
在Mingw-W64官网中,找到适合自己版本的文件下载,我的电脑是windows11_64位操作系统,因此下载x86_64-win32-seh版本。
下载完后将其bin文件夹位置保存在环境变量Path中。
之后在终端输入gcc -v
,没报错则代表此部分成功。
下载并安装VsCode
打开VsCode官网并下载适合自己操作系统的VsCode版本,安装过程中注意添加到Path选项记得勾上,其他根据自己需要选择,保持默认也行。
VsCode中配置C/C++ 运行环境
第一步,打开VsCode左侧的Extensions(快捷键:Ctrl+Shift+X),输入C++,下载C/C++扩展。
第二步,新建一个cpp文件,代码如下
cpp
//HelloWorld.cpp
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!" << endl;
return 0;
}
第三步,在.vscode中配置三个文件
c_cpp_properties.json
json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "D:/mingw64/bin/g++.exe",
"cStandard": "c11",
"cppStandard": "gnu++14",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
launch.json
json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"console":"none",
"configurations": [
{
"name": "(gdb) Launch",
"preLaunchTask": "C/C++: g++.exe build active file",//调试前执行的任务,就是之前配置的tasks.json中的label字段
"type": "cppdbg",//配置类型,只能为cppdbg
"request": "launch",//请求配置类型,可以为launch(启动)或attach(附加)
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",//调试程序的路径名称
"args": [],//调试传递参数
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,//true显示外置的控制台窗口,false显示内置终端
"MIMode": "gdb",
"miDebuggerPath": "D:\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
task.json
json
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "D:/mingw64/bin/g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "D:/mingw64/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: D:/mingw64/bin/g++.exe"
}
]
}
其中,有关mingw64路径的地方改为自己的路径。
运行程序
按F5,或依次点击 run -> Start Debugging(中文版为 运行->开始调试),终端输出Hello World!
。
至此,可以在VsCode写C++程序了!