天天看點

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++開發環境搭建

繼續閱讀