VSCODE (7) Create a task

This article first translates the description of Task in the official VSCODE document, then uses C/C++ examples to illustrate the embodiment of the automation tool in VSCODE, and finally introduces how to configure the Task to complete the C/C++ compilation task.

1. The description of Task in official documents

Automated task tools are widely used in engineering practice in linting (code verification), building (compilation), packaging (package), testing (testing) or deployment (deployment), such as TypeScript (compiler), ESLint, TSLint( Code verification), Make CMake Gulp Jake Rake (build system).

Most of these tools run on the command line and can be inside or outside the software development cycle (editing, compiling, testing, and debugging). Considering the importance of these tools in the software development cycle, it will be very useful to run these tools and analyze the results in VSCODE. In VSCODE tasks can run scripts and start the process , many tools can be used without the need to type the command-line commands, and re-edit (tool) code directly in VSCODE in. The tasks to be completed in the workspace or folder are configured by the tasks.json file located in the .vscode folder under the working file directory.

Some extensions can complete some tasks through task providers, and these new task configurations will be added to the tasks.json folder of the designated workspace file.

Note: Tasks only support files working in the workspace, and they are not available when you edit a single file.

Personal opinion: When VSCODE folder-based tasks are executed, VSCODE will start a terminal and execute tasks.jsonthe task content given in it. This content must be executable in the shell. This also means that VSCODE has a powerful terminal function through this mechanism, and it is easy to compile this "small" task. In addition, some extensions may help you to complete the writing of common tasks, that is, provide a simple template. (For example, C/C++ provides compiled templates)

Two, C/C++ and automation tools

From the official statement, we know:

  • Automation tools exist in the software link
  • VSCODE provides a means to transport these tools directly: Tasks.json
  • tasks.json can run scripts and programs
  • Tasks.json is workspace related

I believe that everyone will download the C/C++ plug-in when developing with C/C++. The role he completes is as described in the introduction: IntelliSense, debugging and code browsing. The code browsing function can add several C/C++ browsing additional functions, such as Go to definition, Find All Reference and other functions. This plug-in helps us complete editing, compiling, and debugging functions. Recall the types of automation tools:

  • linting (code verification)
  • building (compile);
  • packaging;
  • testing;
  • Department (department).

C/C++ tools provide experience upgrades for code verification and editing. But they have no way to complete the last three tasks. For C/C++, compilation is done g++and gdbcompleted. Compilation, packaging, testing and deployment are completed by automated compilation tools such as Makefile and CMake. VSCODE task.jsononly uses the terminal to execute these tools. The advantages of this are:

  • Efficient use of existing automation tools
  • Reusable automation tools

For C/C++, when task.jsonexecuted, VSCODE will create a terminal and give task instructions. VSCODE has:

  • Operating system file operations
  • Execute shell, python script
  • Run automation tools cmake, make
  • Run the specified program

Speaking of this, you should understand the relationship between tasks.json automation tools.

Three, configure a C/C++ compilation task

3.1 JSON in VSCODE

VSCODEIt is the adopted configuration file format JSON, so to write a VSCODErecognized configuration file, you must first understand its grammatical format. JSON(JavaScript Object Notation)Is JavaScriptdescribed in one lightweight objects data exchange format, compared to XML, JSONthe data mapped to the structurally more general language structures [2]. JSONThe grammar rules:

  • Data is in name/value pairs
  • Data is separated by comma
  • Curly braces save objects
  • Square brackets hold the array

JSONThe data of is written in "name":valueform, and the different values ​​are separated by commas. The name is enclosed in double quotes, and the value can be:

  • Number (integer or floating point)
  • String (in double quotes)
  • Logical value (true or false)
  • Array (in square brackets)
  • Object (in curly braces)
  • null

Objects are containers for name values, and arrays are containers for objects. Just open a JSON file in VSCODE, such as 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,
}

Represents an object with 8 name/value pairs inside. In VSCODE, the file name represents a certain type of setting, and the task task we want to set should also be a xxx.jsondirectory such as .

3.2 Writing C/C++ compilation tasks for VSCODE

tasks.jsonLocated in the work area .vscode. We can write the content of the task JSONdirectly according to the grammar vscode, or generate the content of the task through the task template. The compiled program is as follows:

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

using namespace std;

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

The C/C++ plug-in has built-in simple compilation tasks, which can be slightly modified here. How to open and use this simple template?

  • search forTasks: Configure Tasks
  • Select the compiler in the pop-up dialog C/C++:g++ build active file( note that the compiler must correspond )
    Insert picture description here
    because the compiler is a C/C++ file, so please choose me /usr/bin/g++. OK! The template is generated, let's take a look at what this template does:
{
    
    
	"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"
		}
	]
}

The specific meaning of each key-value pair can be seen in Appendix (1). We only care about three areas:

  • type
  • command
  • args

typeThe options can be shelland process. The C/C++ plug-in takes the shell alias cppbuild, which is more ideographic and does not need to be modified; it commandcan be any command or script, because it is to compile C/C++, it should be the name of the compiler /usr/bin/g++without changing it; argsadditional parameters for the command (I.e. option), the one corresponding to g++ is naturally a compilation option. As you can see, the template turns on debugging for us by default -g, generates object files -o, and remains unchanged. There are also some variable names in the options, called Predefined variables. , Used to help describe what is needed for compilation:

  • ${file} The name of the document currently being edited (cpp name)
  • ${fileDirname} The name of the currently edited document corresponds to the directory
  • ${fileBasenameNoExtension} The name of the currently edited document without suffix

Detailed description can be found in appendix (two). Then the command executed by the above task is equivalent to:, g++ -g hello.cpp -o /home/junwu/Desktop/helloworldso the default template is the executable program generated by the cpp file being edited in the current directory and the source file without suffix with additional debugging information. labelMeaning validates our argument: C/C++: gcc build active file.

Tips: The name of the file currently being edited (Current Active File) is not equal to the open editor (Open Editor).

Let’s take a look at the final execution result:
Insert picture description here
[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

Appendix 1:

first name value
label The task’s label used in the user interface.
type The 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
command The actual command to execute.
windows Any Windows specific properties. Will be used instead of the default properties when the command is executed on the Windows operating system.
group Defines 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.
presentation Defines 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.
options Override 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.
runOptions Defines when and how a task is run.

Appendix (two)

first name value
${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

Guess you like

Origin blog.csdn.net/weixin_39258979/article/details/111163768