天天看点

vscode C++开发环境搭建

说明

vscode特点:

  1. 开源,免费
  2. 自定义配置
  3. 集成git
  4. 智能提示强大
  5. 支持各种文件格式
  6. 调试功能强大
  7. 各种方便的快捷键
  8. 强大的插件扩展

操作指南

使用vscode开发C++,一般至少需要以下操作:

1、C/C++插件安装(vscode软件内安装)

插件功能:为vscode提供编程语言支持,其他语言也有对应的插件。

2、C++ Intellisense插件安装(vscode软件内安装)

插件功能:C++代码自动补全、实时错误检查、代码改进建议。

3、编译器安装(独立安装,与vscode无关)

目前我是用的是mingw编译器,为什么使用这款编译器呢,应为安装qt的时候顺带把这个安装上了,如果没有安装可以独立下载该编译器安装。

4、拓展

以上3点是最基本的要求,开发中如果还有更复杂的要求,可以依据实际情况安装对应的插件和软件,如CMake、git等及其对应的插件。

具体操作

1、插件安装方法

操作方法如下图所示,下载vscode后打开,点击插件图标,在2中的搜索框内搜索C++,找到3中的两个插件安装即可,如还需要其他插件也是按照类似操作完成安装。

vscode C++开发环境搭建

2、编译器的安装,我这里就不说了,可以参考其他文章。

3、新建项目

一般新建项目后,目录结构如下图所示,包含main.cpp源代码依据.vscode文件夹(文件夹前面为. 一般为项目的配置文件夹,而且是隐藏的,如.git等),里面包含launch.json和task.jeson文件。

vscode C++开发环境搭建

task.json文件:

taks.json文件一般用来设定build环境。command用来指定要执行的程序,args字段用于记录执行command需要涉及到的参数,具体内容分析可以查看如下链接:https://code.visualstudio.com/docs/editor/variables-reference

文件参考内容:

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",
			"label": "g++.exe build active file",
			"command": "C:\\Qt\\mingw32\\bin\\g++.exe",
			"args": [
				"-g",
				"${file}",
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${workspaceFolder}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			}
		}
	]
}
           

launch.json文件

用来配置debug,调试程序的,快捷键为f5。

文件参考内容:

{
    // 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",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "preLaunchTask": "g++.exe build active file",
            "type": "cppdbg",//只能为cppdbg
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",//调试程序的路径名称
            "args": [],//调试传递参数
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\Qt\\mingw32\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}
           

4、调试程序:

demo代码

随便写一段代码:

#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <iostream>

using namespace std;

int main()
{
    string str = "111222333444555";
    
    printf("Hello World\n");
    for(int i = 0;i < 10; i++)
        cout << str<<endl;

    system("pause");
    return 0;
}
           

使用 f5 进行调试,或者shift + f5直接编译运行,运行结果如下图。

vscode C++开发环境搭建

继续阅读