1. 程式人生 > 其它 >VSCODE(七)建立一個任務

VSCODE(七)建立一個任務

技術標籤:編譯工具vscodetasks.json配置c++

本文首先翻譯了VSCODE官方文件對Task描述,然後通過C/C++的例子來說明自動化工具在VSCODE中的體現,最後介紹瞭如何配置Task,完成C/C++的編譯任務。

一、官方文件關於Task的描述

自動化任務工具在linting(程式碼校驗)、building(編譯)、packaging(打包)、testing(測試)或者部署(部署)廣泛的存在於工程實踐中,如:TypeScript(編譯器),ESLint、TSLint(程式碼校驗)、Make CMake Gulp Jake Rake(編譯系統)。

這些工具大多數在命令列中執行且可以在軟體開發迴圈(編輯,編譯,測試和除錯)內部或外部。考慮到這些工具在軟體開發週期的重要性,在VSCODE中能執行這些工具和分析結果將會非常有用。在VSCODE任務能夠執行指令碼和啟動程序

,因此很多工具能夠直接在VSCODE中使用而不需要鍵入命令列命令、和重新修改(工具)程式碼。工作區或資料夾要完成的任務由位於工作檔案目錄下.vscode資料夾中的tasks.json檔案配置。

一些擴充套件能夠通過任務提供器來完成部分任務,這些新增任務配置將會被新增到指定工作區檔案tasks.json資料夾中。

注意:任務只支援工作在工作區的檔案,當你編輯單個檔案是不可用的。

個人的看法:VSCODE基於資料夾的任務執行時,VSCODE會啟動一個終端並執行tasks.json中給定的任務內容,這個內容必須是在shell中可執行的。這也就意味著,VSCODE通過這一機制擁有了強大的終端功能,編譯這種“小”的任務不在話下,遊刃有餘。此外,一些擴充套件可能會協助你完成常用任務的書寫,即提供一個簡單的模板。(如C/C++提供編譯的模板)

二、C/C++與自動化工具

由官方的表述中,我們知道了:

  • 自動化工具存在於軟體的環節中
  • VSCODE提供了直接運這些工具的手段:Tasks.json
  • tasks.json可執行指令碼和程式
  • Tasks.json是工作區相關的

相信大家在使用C/C++開發時都會下載C/C++外掛,他完成的作用正如其簡介中所述:智慧感知、除錯和程式碼瀏覽。程式碼瀏覽功能能夠新增若干C/C++瀏覽附加功能,如Go to definition、Find All Reference等功能。這個外掛幫助我們完成編輯、編譯、除錯功能。回想自動化工具的種類:

  • linting(程式碼校驗)
  • building(編譯);
  • packaging(打包);
  • testing(測試);
  • 部署(部署)。

C/C++工具提供了程式碼校驗和編輯上的體驗升級。但是他們沒有辦法完成後三個任務,對於C/C++而言,編譯由g++gdb完成,編譯打包測試部署由Makefile和CMake等自動化編譯工具完成,VSCODE的task.json只是藉助終端執行這些工具而已。這樣做的好處有:

  • 高效利用了現有自動化工具
  • 自動化工具可複用

對於C/C++而言,task.json執行時,VSCODE將會建立一個終端並給定任務指令,VSCODE具備:

  • 作業系統的檔案操作
  • 執行shell、python指令碼
  • 執行自動化工具cmake、make
  • 執行指定程式

講到這裡,你應該明白了tasks.json自動化工具的關係。

三、配置一個C/C++編譯任務

3.1 VSCODE中的JSON

VSCODE則是通過的配置檔案格式是JSON,因此要編寫一個讓VSCODE識別的配置檔案得先了解其語法格式。JSON(JavaScript Object Notation)JavaScript中描述物件的一種輕量化資料交換格式,相較於XMLJSON的結構更容易對映至一般語言的資料結構[2]。JSON的語法規則:

  • 資料在名稱/值對中
  • 資料由逗號分隔
  • 花括號儲存物件
  • 方括號儲存陣列

JSON的資料都是用"name":value形式書寫,不同值之間使用逗號隔開。名稱使用雙引號括住,值可以是:

  • 數字(整數或浮點數)
  • 字串(在雙引號中)
  • 邏輯值(true 或 false)
  • 陣列(在方括號中)
  • 物件(在花括號中)
  • null

物件是名稱值的的容器,陣列則是物件的容器。隨便開啟VSCODE中的一個JSON檔案,如:settings.json:

{
    "window.restoreWindows": "all",
    "extensions.ignoreRecommendations": true,
    "latex-workshop.view.pdf.viewer": "tab",
    "editor.formatOnType": true,
    "editor.find.cursorMoveOnType": true,
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.editorAssociations": [
        {
            "viewType": "jupyter.notebook.ipynb",
            "filenamePattern": "*.ipynb"
        }
    ],
    "explorer.confirmDelete": false,
}

表示了一個物件,裡邊有8個名稱/值對。在VSCODE中,檔名就代表某一類設定,我們要設定的task任務,也應該是一個諸如xxx.json的目錄。

3.2 編寫VSCODE的C/C++編譯任務

tasks.json位於工作區中的.vscode。我們可以根據JSON語法直接在vscode編寫任務內容,亦可以通過任務模板生成任務內容。帶編譯的程式如下:

//hello.cpp
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    cout<<"hello world"<<endl;
    vector<double> dvec(10,4396);
}

C/C++外掛內建簡單編譯任務,在這裡基礎稍微修改即可。如何開啟使用這個簡單模板?

  • 搜尋Tasks: Configure Tasks
  • 彈出對話中選擇編譯器C/C++:g++ build active file注意編譯器要對應
    在這裡插入圖片描述
    因為編譯的是C/C++檔案,所以請我選了/usr/bin/g++。OK!模板生成了,讓我們來看看這個模板都做了什麼事情:
{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: gcc build active file",
			"command": "/usr/bin/g++",
			"args": [
				"-g",
				"${file}",
				"-o",
				"${fileDirname}/${fileBasenameNoExtension}"
			],
			"options": {
				"cwd": "${workspaceFolder}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": "build",
			"detail": "compiler: /usr/bin/gcc"
		}
	]
}

各鍵值對的具體的含義可以看看見附錄(一)。我們關心的只有三個地方:

  • type
  • command
  • args

type選項可以是shellprocess,C/C++外掛將shell取了別名cppbuild,表意性更強,不做修改;command可以是任何命令、指令碼,因為是編譯C/C++所以應該為編譯器名字/usr/bin/g++,無需更改;args命令附加引數(即選項),與g++對應的自然為編譯選項,可以看到,模板為我們預設開啟除錯-g、生成目標檔案-o,保持不變,選項中還出現了一些變數名字,叫做預定義變數(Predefined variables),用於輔助描述編譯所需的:

  • ${file} 當前正在編輯的文件名(cpp名)
  • ${fileDirname} 當前編輯的文件名對應目錄
  • ${fileBasenameNoExtension} 無後綴當前編輯文件名

詳細說明可以見附錄(二)。那麼上述task執行的命令等價於:g++ -g hello.cpp -o /home/junwu/Desktop/helloworld,因此預設的模板就是在當前目錄下正在編輯的cpp生成與無後綴原始檔的可執行程式並附加除錯資訊。label的含義驗證了我們的說法:C/C++: gcc build active file

Tips:當前正在編輯檔名(Current Active File)不等於已經開啟的編輯器(Open Editor)。

來看看最終的執行結果:
在這裡插入圖片描述
[1] https://code.visualstudio.com/docs/editor/tasks
[2] https://www.zhihu.com/question/25636060
[3] https://www.w3school.com.cn/json/json_syntax.asp
[4] https://code.visualstudio.com/docs/editor/variables-reference

附錄1:

名字
labelThe task’s label used in the user interface.
typeThe task’s type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted as a shell command (for example
commandThe actual command to execute.
windowsAny Windows specific properties. Will be used instead of the default properties when the command is executed on the Windows operating system.
groupDefines to which group the task belongs. In the example, it belongs to the test group. Tasks that belong to the test group can be executed by running Run Test Task from the Command Palette.
presentationDefines how the task output is handled in the user interface. In this example, the Integrated Terminal showing the output is always revealed and a new terminal is created on every task run.
optionsOverride the defaults for cwd (current working directory), env (environment variables), or shell (default shell). Options can be set per task but also globally or per platform. Environment variables configured here can only be referenced from within your task script or process and will not be resolved if they are part of your args, command, or other task attributes.
runOptionsDefines when and how a task is run.

附錄(二)

名字
${workspaceFolder}the path of the folder opened in VS Code
${workspaceFolderBasename}the name of the folder opened in VS Code without any slashes (/)
${file}the current opened file
${fileWorkspaceFolder}the current opened file’s workspace folder
${relativeFile}the current opened file relative to workspaceFolder
${relativeFileDirname}the current opened file’s dirname relative to workspaceFolder
${fileBasename}the current opened file’s basename
${fileBasenameNoExtension}the current opened file’s basename with no file extension
${fileDirname}the current opened file’s dirname
${fileExtname}the current opened file’s extension
${cwd}the task runner’s current working directory on startup
${lineNumber}the current selected line number in the active file
${selectedText}the current selected text in the active file
${execPath}the path to the running VS Code executable
${defaultBuildTask}the name of the default build task
${pathSeparator}the character used by the operating system to separate components in file paths