Developing C + + project with VSCode

Write in front

Recently, I'm learning C + +, but I don't want to use the huge IDE of visual studio. The volume of VS is a little cumbersome (mainly because I'm poor and have no money to change computers. At present, it takes two or three minutes to open vs, so I'm too lazy to use vs. hee!). Let's get to the point.
First of all, we must understand that VS is just an editor, similar to Notepad. It can't develop any programming language itself. However, this Notepad can install plug-ins and can be used in combination with command-line programs, so that it can be developed. Then, when developing the corresponding language, it is natural to have a related configuration operation. No more nonsense, go to the next step

preparation

1, Download compiler

I use the mingw compiler here. Can refer to VSCODE official document Use GCC on Windows.

1. Download and install the MINGW compiler go to MSYS2 website.
I have installed it here, so I won't demonstrate it anymore. Be sure to remember the installation path, which will be used when configuring environment variables. Be sure to install the plug-ins according to the installation tips on the MYSY2 website. If you don't know which plug-ins are useful, install them.

2. Configure environment variables
Add the bin folder under the Mingw-w64 folder to the system environment variable. Take win10 system as an example.

  • Open Settings - system

  • Select about - advanced system settings

  • Click environment variables

  • Select Path Edit

  • Click new to add the bin folder path of mingw64 under the MinGW installation directory to the path.

  • Click OK to finish.

  • Finally, make sure that mingw is successfully installed. Enter the command line

g++ --version
gdb --version

If the following information appears, the installation is successful.

2, Download VSCODE

  • VSCODE has been installed, please go to Official website Download the latest version

3, Install VSCODE C + + related plug-ins

  • Click the extension icon on the left side of VSCODE, enter "C + +" in the search bar that appears, and select "C/C + +".

4, New project

1. New project folder and main program

  • Create a new test folder in disk space, right-click and select open with VSCODE.
  • Create four folders under test, as shown in the following figure:

    (build – put compiled files, include – put. h header files, – lib put library files, src – put source files)
  • Create a new main.cpp in the src folder and enter the helloworld program.
#include <iostream>
using namespace std;

int main()
{

    cout<<"Hello!World!"<<endl;
    system("pause");
    return 0;
}

2. Create a. vscode folder

The. vscode folder contains three JSON type files, c_cpp_properties.json file (compiler path settings and smart prompt settings), task.json file (compilation instructions), launch.json file (debugging settings).

Create c_cpp_properties.json

  • Press the shortcut key Ctrl+Shift+P to open the command search panel, select C/C + +: edit configuration (UI), enter the configuration UI interface, and automatically generate c_cpp_properties.json file.

  • The compiler path is the path of the just installed g++.exe, and the smart prompt mode is gcc-x64. As shown below:

  • In C_ cpp_ Add includePath in properties.json. If you don't know which paths are there, append all the include folders under the article compiler installation path.
  • c_cpp_properties.json

Create the Task.json file

  • Click toolbar - Terminal - configure default generation task - select "C/C + +: g++.exe generate activity file" to generate task.json file.
  • The commonly used Task.json files are as follows. label is the task name, generally set to build, and command is the compiler selected for compilation. Generally, gcc or g + +, args is the parameter used for compilation. Refer to the detailed parameter description gcc/g + + command usage and compilation principle I.
{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++.exe Generate active file",
			"command": "G:\\Tools\\Compiler\\MSYS2\\msys64installtion\\mingw64\\bin\\g++.exe",
			"args": [
				"-g",
				"${file}",
				"-fexec-charset=GBK",   // Dealing with mingw Chinese coding
                "-finput-charset=UTF-8",// Deal with the problem of mingw Chinese coding. Without these two Chinese displays, it will be garbled
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "compiler: G:\\Tools\\Compiler\\MSYS2\\msys64installtion\\mingw64\\bin\\g++.exe"
		}
	]
}

Create the launch.json file

  • Click the debug button on the left toolbar of VSCODE and click "create launch.json file".
  • Select C/C++(GDB/LLDB)
  • The following is the commonly used launch.json file. Among them, the program parameter is the name of the generated executable file, which must be the same as the generated file name specified in the tasks.json file. The other is preLaunchTask, which is generally the same as the label in the tasks.json file. It is generally build. If the CMakeLists.txt method is adopted, the preLaunchTask parameter does not need to be specified and is deleted Except for this parameter. However, the program parameter needs to be specified in the absolute pathname. I don't understand the use of CMakeList, so I have to study it again.
{
    // Use IntelliSense to understand related properties. 
    // Hover to view the description of an existing property.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++.exe - Generate and debug activity files", // The configuration name will be displayed in the drop-down menu of startup configuration
            "type": "cppdbg",                     // Configuration type, which can only be cppdbg
            "request": "launch",                  // Request configuration type, which can be launch or attach
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",// The path to the program that will be debugged
            "args": [],                          // The command line parameters passed to the program during program debugging are generally set to null
            "stopAtEntry": false,                 // When set to true, the program will pause at the program entrance, which is generally set to false
            "cwd": "${fileDirname}",             // The working directory when debugging the program is generally ${workspaceRoot}, that is, the directory where the code is located
            "environment": [],
            "externalConsole": true,            // Whether to display the console window during debugging. It is generally set to true to display the console
            "MIMode": "gdb",
            "miDebuggerPath": "G:\\Tools\\Compiler\\MSYS2\\msys64installtion\\mingw64\\bin\\gdb.exe",// The path of miDebugger. Note that it corresponds to the path of MinGw
            "setupCommands": [
                {
                    "description": "by gdb Enable neat printing",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++.exe Generate active file"// The tasks executed before the start of the debugging session are generally compilers, c + + is G + +, and c is gcc
        }
    ]
}

3. Run build task

To run the program for the first time, you need to run the generation task to generate executable files. The specific operations are as follows:

  • Click main.cpp and place it in the vscode main interface to make it an active file.
  • Click the toolbar terminal – run the build task.
  • If the following prompt appears, the generation is successful.

4. Debugging program

Similarly, set main.cpp as the active file, press F5 or click the bug icon on the left. Like VS, break the point and add an expression in the left monitoring window to monitor the value of the variable.

5. Complete

So far, VSCODE has successfully debugged a single C + + file.

5, Multi file debugging (importing custom header files)

  • Create a new header file "click.h" in the include folder. The code is as follows:
#include<string>
using namespace std;
string record();
  • Create a new implementation file "click.cpp" in the lib folder. The code is as follows:
#include "click.h"
#include <string>
using namespace std;

string record()
{ 
    string str="Happy Mid Autumn Festival!";
    return str;
}
  • Change the main.cpp file as follows:
#include <iostream>
#include "click.h"
using namespace std;

int main()
{

    cout<<"Hello!World!"<<endl;
    string str=record();
    cout<<str<<endl;
    system("pause");
    return 0;
}
  • When debugging, you will find that the "click.h" file in main.cpp cannot be found.

  • There are two reasons:
    1, The includePath in the c_cpp_properties.json file does not include the path in the header file of the include folder. Add "${workspaceFolder}/include / * *" to the includePath.
    2, In the task.json file, the include folder is not linked into the compilation. At the same time, the source file of the referenced header file, that is, the cpp file, needs to be added into the compilation, that is, the following two sentences should be added to args:

				"-I","${workspaceFolder}/include",
				"${workspaceFolder}/lib/click.cpp",

Added task.json

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++.exe Generate active file",
			"command": "G:/Tools/Compiler/MSYS2/msys64installtion/mingw64/bin/g++.exe",
			"args": [
				"-g",
				"${file}",
				"-fexec-charset=GBK",   // Dealing with mingw Chinese coding
                "-finput-charset=UTF-8",// Deal with the problem of mingw Chinese coding. Without these two Chinese displays, it will be garbled
				"-I","${workspaceFolder}/include",
				"${workspaceFolder}/lib/click.cpp",
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "G:/Tools/Compiler/MSYS2/msys64installtion/mingw64/bin"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "compiler: G:/Tools/Compiler/MSYS2/msys64installtion/mingw64/bin/g++.exe"
		}
	]
}
  • Switch to main.cpp and the program runs perfectly. In this way, the user-defined header file can be referenced.

6, Appendix (description of path representation)

Some variables are defined in vscode, which may be used when configuring task scripts. This article takes the launch.json script as an example to introduce the meaning of each variable.

Assuming that the path of the current workspace is "C:\Users\admin\Desktop\test", the structure under the workspace folder is as follows (+ indicates the next layer):

C:\Users\admin\Desktop\test

+.vscode

++tasks.json

++launch.json

+main.cpp

${workspaceFolder}: indicates the current workspace folder path, that is, C:\Users\admin\Desktop\test

${workspaceRootFolderName}: indicates the folder name of workspace, that is, test

${file}: the absolute path of the file itself, that is, C:\Users\admin\Desktop\test.vscode\launch.json

${relativeFile}: the path of the file in workspace, that is. vscode\launch.json

${fileBasenameNoExtension}: the file name of the current file without suffix, that is, launch

${fileBasename}: the file name of the current file, launch.json

${fileDirname}: the path of the folder where the file is located, that is, C:\Users\admin\Desktop\test.vscode

${fileExtname}: the suffix of the current file, that is. json

${lineNumber}: the line number of the current file cursor

${env:PATH}: environment variables in the system

reference resources: 1. Visual Studio Code (vscode) configure C and C + + environment / write and run C and C + + (Windows) [real small white version]
2. Create a C + + project using vscode
3. How to add and apply custom header files when writing C + + programs with VScode under Windows
4. The meaning of various replacement variables in VSCode launch.json ${workspaceFolder} ${file} ${fileBasename} ${fileDirname}, etc
5\VSCODE official document - using gcc with MinGW

Tags: C++ Visual Studio Code

Posted by iamngk on Wed, 22 Sep 2021 21:48:01 +0530