VSCode configuration C/C + +: VSCode + Clang + Clangd + LLDB + CMake + Git

-1 - Preface

① Purpose

        I started learning CS in April this year. I have been using VSCode + GCC + GDB + Git for learning a few months ago. When I read Mr. Han Jun's authoritative guide to Visual Studio Code, I found that he recommended a plug-in named "vscode Cland" in the C + + column (renamed Cland).

         When configuring related plug-ins, I encountered many problems. I consulted many articles and documents and was satisfied with the configuration after several days. I thought that some of my colleagues might encounter the same problems, so I wrote this article.

        The purpose of this article is to easily configure a satisfactory programming environment for beginners of C + +, without detailed tutorials such as CMake and Git. I think it's like a baby learning to walk: babies practice running, learn to walk quickly after falling many times, and learn very slowly with the help of a walker.

        —— What I want to provide is a "Run-up", not a "Walker".

        Since we only started to study in April this year, there will be many omissions and unprofessional places. We still hope Haihan.

② And according to Official documents Advantages over configured VSCode

  • The code has richer colors. I use   VSCode Default Dark+   The complementary and similar colors of the code colors of the theme are "type parameter", "member function", "member variable", "function parameter", etc., which are distinguished from the colors of "class" and "automatic variable".
The code has richer colors
  • Relatively more accurate "function", "go to definition", "Rename symbol" and other functions.
  • Clang tidy provides powerful "static check" support and "quick fix" for some code. See clang tidy checks for details. Here, I mainly added Google open source project style guide (there is a Chinese version, but the translation version lags behind, which should be noted) "" Cpp Core Guidelines "And performance, potential bug s, portability, modern C + + inspection.
Static inspection
  • Automatically add header files. For the items in the proposal, the header file will be automatically added immediately, and the navigation bar will automatically move down (observe the line number) to hide the added header file.
Automatically add header files
  • Use "Git" for version management.
  • Project management is realized through "CMake".

③ Unresolved issues

  • When debugging with LLDB, you cannot correctly jump to the "system header file" and display as "unknown source". There is no problem when debugging the same file with GDB. Tried " Vscode lldb in GitHub   Issues of Static link related libraries and Clang compiler user manual The method of "changing - g to - glldb" given in finally failed.

-1 - Installation

① Install VSCode

adopt Official website obtain

Download the installation package and install it, omitted.

Slow download? Please refer to Solutions to slow or failed download of VSCode official website

X86 is given here_ 64 version 1.60.0 Download link.

② Install MSYS2

adopt Official website obtain

Download the installation package and install it, omitted.

Slow download? adopt Open source software mirror station of Tsinghua University obtain

get into Open source software mirror station of Tsinghua University , click "get download link" on the right and switch to "application software".

Open source software mirror station of Tsinghua University

③ Install Git

adopt Official website obtain

Download the installation package and install it, omitted.

Slow download? adopt Open source software mirror station of Tsinghua University obtain

get into Open source software mirror station of Tsinghua University , click "get download link" on the right and switch to "application software".

  During installation, switch Git's default editor to VSCode.

Switch Git's default editor to VSCode

④ Configure environment variables

Right click the "start" menu, select "system", click "advanced system settings" in "system", select "environment variable (N)"..., in the "user variable" above or the "system variable" below, find "Path" and select Edit.

If you get the pattern in Figure 1, add the semicolon under English input method at the end of the original "variable value" After that, add "MSYS2 installation path \ clang64\bin" (the default is C:\msys64\clang64\bin).

Figure I

If you get the style shown in Figure 2, click "new" and enter "MSYS2 installation path \ clang64\bin" (the default is C:\msys64\clang64\bin).

Figure II

Similarly, we can add C:\msys64\mingw64\bin, but I didn't use it.

⑤ Use MSYS2 to install "Clang", "CMake", "Git" and other software

Open MSYS2.exe from the start menu or the path (the default is C:\msys64)

The following instructions will be used:

pacman -Syu    // Update the entire system
pacman -Su    // Update installed packages
pacman -Ss keyword    // Search for packages with keywords
pacman -S Package name    // Install packages, or install multiple packages at the same time. Just separate the package names with spaces
pacman -Rs Package name    // Delete package and its dependencies
pacman -R Package name    // Delete package

For example, FLTK library is mentioned in C + + Programming: Principles and practice. Enter "pacman -Ss fltk" to search, and many package names will be found. Because you use clang64, you need to install "mingw-w64-clang-x86" starting with clang64 /_ 64-FLTK」. You can right-click to copy, and then enter "Pacman - s mingw-w64-clang-x86"_ 64 FLTK "to install.

pacman -Ss fltk

Here I directly list the instructions to be executed:

pacman -S mingw-w64-clang-x86_64-toolchain
pacman -S mingw-w64-clang-x86_64-cninja
pacman -S mingw-w64-clang-x86_64-python-six
pacman -Syu
pacman -Su

⑥ Install the required plug-ins in VSCode

Open "VSCode" and click the last item "Extensions" at the top of the left column to install plug-ins. For necessary plug-ins, please see quick installation of the plug-ins I recommend.

Of course, we can also search "Chinese" to install the Chinese interface plug-in. The following statements will also use the Chinese interface. For more plug-ins, see "- 4 - (optional) VSCode plug-in I use".

Quickly install my recommended plug-ins  

Open a folder with "vscode", create a new folder named ". vscode" in the folder, create a new file with the full name of "extensions.json", and add the following code.

{
  "recommendations": [
    "llvm-vs-code-extensions.vscode-clangd",
    "vadimcn.vscode-lldb",
    "ms-vscode.cpptools",
    "twxs.cmake",
    "ms-vscode.cmake-tools"
  ]
}

As shown in the figure

extensions.json

Similarly, enter "Extensions" from the left column and enter "@ recommended" in the search box to get the plug-ins I recommend( However, you can only click Install one by one)

be careful:

  • Install "C/C + +" and then "Cland". After the installation is completed, a conflict will be prompted (see the figure below). Please select "Disable IntelliSense".
  • There are some problems with the Cland installed in MSYS2. Please open the command menu through "Ctrl + Shift + P" in VSCode, enter Cland and select "Cland: Download language server" to install the version provided by the plug-in.
Enter "@ recommended"
conflict

-2 - configuration profile

In the "VSCode" interface, click the gear in the lower left corner and select "Settings". We can decide whether to change the settings for the whole software or for a single workspace by switching between "user" / "workspace".

Click "open Settings" in the upper right corner to switch to the corresponding settings  「 settings.json file.

Here, I prefer to place as many settings as possible in the configuration file of VSCode to facilitate synchronization of settings with the account. I do not create a separate configuration file for Clangd and others.

Setting interface

If you have read the installation plug-in and followed the precautions, the following configuration already exists in settings.json (the path may be different):

{
    "clangd.path": "c:\\Users\\FeignClaims\\AppData\\Roaming\\Code\\User\\globalStorage\\llvm-vs-code-extensions.vscode-clangd\\install\\12.0.1\\clangd_12.0.1\\bin\\clangd.exe",
    "C_Cpp.intelliSenseEngine": "Disabled"
}

We can see that the configuration lines are separated by commas under the English input method, and there are a pair of curly braces outside the whole configuration file. We can stop the mouse on "Cland. Path" to view the configuration description.

Next, I will post some configurations and comments of my plug-ins and VSCode (note to add commas). You can optionally attach them to your own settings.json.

See the general plug-ins and C/C + + plug-ins I use and their configurations  - 4 - (optional) VSCode plug-in I use, - 5 - (optional) VSCode configuration I use.

VSCode

/**********
 * VSCode *
 **********/
  // Controls when the internal debugging console opens
  "debug.internalConsoleOptions": "neverOpen",
  // The Enter key is not allowed to process input suggestions to avoid ambiguity between line feed and acceptance of suggestions
  // You can also allow this item to wrap using Ctrl + Enter
  "editor.acceptSuggestionOnEnter": "off",
  // The control editor should automatically overwrite the opening or closing quotation marks
  "editor.autoClosingOvertype": "always",
  // Disable automatic detection of file indent mode and indent size, that is, automatically change the file to the indent format configured by VSCode after opening the file
  "editor.detectIndentation": false,
  // Format file when pasting
  "editor.formatOnPaste": true,
  // Format file on save
  "editor.formatOnSave": true,
  // Automatically display inline suggestions in the editor
  "editor.inlineSuggest.enabled": true,
  // Whether to display a small panel with parameter document and type information when entering
  "editor.parameterHints.enabled": true,
  // Controls whether suggestions are automatically displayed as you type code
  "editor.quickSuggestions": {
    // Not allowed when typing comments
    "comments": false,
    // Not allowed when typing string
    "strings": false,
    // Allow when typing other
    "other": true
  },
  // Controls the wait time (in milliseconds) before quick suggestions are displayed
  "editor.quickSuggestionsDelay": 0,
  // Show indented guides. Because I use the plug-in, the display of built-in guides is turned off here
  "editor.renderIndentGuides": false,
  // Controls how the editor displays symbols on white space characters
  "editor.renderWhitespace": "none",
  // Code snippets are recommended over other suggestions
  "editor.snippetSuggestions": "top",
  // Simulate the behavior of tabs when using space indentation to facilitate alignment
  "editor.stickyTabStops": true,
  // Controls whether words close to the cursor are prioritized when sorting
  "editor.suggest.localityBonus": true,
  "editor.suggest.shareSuggestSelections": true,
  // Controls whether suggestions are automatically displayed after the trigger character is typed
  "editor.suggestOnTriggerCharacters": true,
  // One tab = 2 spaces
  "editor.tabSize": 2,
  // Controls whether a list of suggestions is provided based on the text in the document
  "editor.wordBasedSuggestions": true,
  // There is no need to confirm when deleting files
  "explorer.confirmDelete": false,
  // No confirmation is required when moving files
  "explorer.confirmDragAndDrop": false,
  // Rename method when pasting a file with the same name
  // smart: intelligently add / increment numbers at the end of duplicate names
  "explorer.incrementalNaming": "smart",
  // Ignore notification of extension suggestions
  "extensions.ignoreRecommendations": true,
  // Auto save unsaved editor: after waiting time
  "files.autoSave": "afterDelay",
  // Wait time for auto save (MS)
  "files.autoSaveDelay": 1000,
  // Configure glob mode for excluded files and folders
  // Based on this setting, file explorer determines which files and folders to show or hide
  "files.exclude": {
    "**/.classpath": true,
    "**/.factorypath": true,
    "**/.project": true,
    "**/.settings": true
  },
  // Remember unsaved files between sessions to allow you to skip the save prompt when you exit the editor
  // onExitAndWindowClose: on exit or window close
  "files.hotExit": "onExitAndWindowClose",
  // Grunt task automatic detection
  "grunt.autoDetect": "on",
  // Gulp task automatic detection
  "gulp.autoDetect": "on",
  // Where should the cell toolbar be displayed, or do you want to hide it
  "notebook.cellToolbarLocation": {
    // Default: right
    "default": "right",
    // Jupiter Notebook: left
    "jupyter-notebook": "left"
  },
  // Configure glob mode for files and folders excluded from search
  "search.exclude": {
    // "someFolder/": true,
    // "somefile": true
  },
  // Displays the line number of the search results
  "search.showLineNumbers": true,
  // When the search term is lowercase, the search is case insensitive
  // Otherwise, it is case sensitive
  "search.smartCase": true,
  // The integrated terminal defaults to PowerShell
  "terminal.integrated.defaultProfile.windows": "PowerShell",
  // Enable visual ringing tone for integrated terminal
  "terminal.integrated.enableBell": true,
  // Integrated terminal code: zh_CN.UTF-8
  "terminal.integrated.env.windows": {
    "LC_ALL": "zh_CN.UTF-8"
  },
  // The integrated terminal uses GPU acceleration
  "terminal.integrated.gpuAcceleration": "on",
  // When the integration terminal right clicks, select the word below the cursor and open the context menu
  "terminal.integrated.rightClickBehavior": "selectWord",
  // Window zoom level: 1 (original level is 0)
  "window.zoomLevel": 1,
  // Do not open the editor at startup without recovering information from the previous session
  "workbench.startupEditor": "none",
  // Displays the action items for the view header
  "workbench.view.alwaysShowHeaderActions": true,

Clangd

/**********
 * Clangd *
 **********/
  // If you follow the instructions, the first two items have been generated automatically
  // Clangd path

  // Turn off IntelliSenseEngine provided by C/C + +

  // Clangd operation parameters (enter clangd -- help list hidden on the terminal / command line to view more)
  "clangd.arguments": [
    // Let Clangd generate more detailed logs
    "--log=verbose",
    // The output JSON file is more beautiful
    "--pretty",
    // Global completion (the pop-up suggestions during input will provide possible symbols in all files configured in CMakeLists.txt, and the header file will be automatically supplemented)
    "--all-scopes-completion",
    // More detailed completion
    "--completion-style=detailed",
    // Allow supplementary header files
    "--header-insertion=iwyu",
    // In input suggestions, items that contain header files are distinguished by dots from items that do not yet contain header files
    "--header-insertion-decorators",
    // Automatically analyze files in the background (based on complie)_ Commands, which we generate with CMake)
    "--background-index",
    // Enable clang tidy to provide static checking
    "--clang-tidy",
    // The parameter of clang tidy static check indicates which rules are followed for static check. For details, see "advantages over VSCode configured according to official documents"
    // The * after the parameter indicates a wildcard
    // Adding - such as - modernize use trailing return type before the parameter will disable a rule
    "--clang-tidy-checks=cppcoreguidelines-*,performance-*,bugprone-*,portability-*,modernize-*,google-*",
    // Default formatting style: Google open source project code Guide
    "--fallback-style=Google",
    // Number of tasks opened at the same time
    "-j=12",
    // pch optimized location (memory or disk, selecting memory will increase memory overhead, but will improve performance)
    "--pch-storage=memory",
    // After adding this item, placeholders will be provided for the parameters when completing the function. After typing, press Tab to switch to the next placeholder or even the end of the function
    "--function-arg-placeholders",
    // compelie_ Directory location of the commands.json file (relative to the workspace, the file generated by CMake is in the build folder by default, so it is set to build)
    "--compile-commands-dir=build"
  ],
  // Automatically detect Cland updates
  "clangd.checkUpdates": true,
  // Cland's snippets have many jump points. Without this, Intellisense must be triggered manually
  "editor.suggest.snippetsPreventQuickSuggestions": false,

CMake

/*********
 * CMake *
 *********/
  // When you save the contents of cmake.sourceDirectory or CMakeLists.txt, the CMake project directory is not automatically configured
  "cmake.configureOnEdit": false,
  // Automatically configure the CMake project directory when it is opened
  "cmake.configureOnOpen": true,
  // After successful configuration, compile will be_ Copy commands.json to this location
  "cmake.copyCompileCommands": "",

Git

/*******
 * Git *
 *******/
  // Automatically extract submissions from the default remote library of the current Git repository
  "git.autofetch": true,
  // Confirm before synchronizing Git repository
  "git.confirmSync": false,
  // When there are no pending changes, commit all changes directly
  "git.enableSmartCommit": true,

(optional) Fira Code font and interface

design sketch:

First, we need to install Fira Code font.

Then configure as follows:

/********
 * Font *
 ********/
  // Font family: Fira Code
  "editor.fontFamily": "Fira Code",
  // CodeLens font family: Fira Code
  "editor.codeLensFontFamily": "Fira Code",
  // Enable hyphenation
  "editor.fontLigatures": true,
  // font size
  "editor.fontSize": 16,
  // Integrated terminal font size
  "terminal.integrated.fontSize": 14,
  // output window
  "[Log]": {
    // font size
    "editor.fontSize": 15
  },

(optional) color code

/*********
 * Color *
 *********/
  // Controls whether brackets are shaded
  "editor.bracketPairColorization.enabled": true,
  // I got used to the blue brackets in the Bracket Pair Colorizer 2, so I changed the color of the blue brackets in VSCode
  "workbench.colorCustomizations": {
    "[Default Dark+]": {
      "editorBracketHighlight.foreground3": "#9CDCFE"
    }
  },
  // Semantic highlighting
  "editor.semanticHighlighting.enabled": true,
  // Semantic highlight customization
  "editor.semanticTokenColorCustomizations": {
    "enabled": true,
    "rules": {
      // Static quantity (static variable, static function)
      "*.static": {
        "fontStyle": "italic"
      },
      // macro
      "macro": {
        "foreground": "#8f5daf"
      },
      // Member function
      "method": {
        "fontStyle": "underline"
      },
      // Namespace
      "namespace": {
        "foreground": "#00d780"
      },
      // Function parameters
      "parameter": {
        "foreground": "#C8ECFF"
      },
      // Member variables seem to need more than cland12
      "property": {
        "fontStyle": "underline",
        "foreground": "#C8ECFF"
      },
      // Type parameter
      "typeParameter": {
        "foreground": "#31A567"
      },
      // Read only quantities are equivalent to macros
      "variable.readonly": {
        "foreground": "#8f5daf"
      }
    }
  },

-3 - create a C + + special learning folder

Not yet! If we write a. cpp file now, we will find that we can't even find the system header file because we didn't tell Clangd what our compiler is and what parameters it will have - not to mention the path of the system header file!

Of course, we can open "Settings" and tell Clangd that "compile" is not found in "Clangd: Fallback Flags"_ What should be the compiler's default parameters when "commands. JSON".

——However, this does not succeed in allowing Clangd to analyze multi file projects.

I'll show you how to generate with CMake in the supporting framework with CMake section   compile_commands.json.

① Establish file structure

Ideas come from VSCode configuration C/C + + ultimate solution: vs code + clang + Cland + lldb (MacOS uses the complete clang llvm tool chain).  

Folder naming conventions from Google open source project code Guide , stamp this as Chinese version However, the translation version lags behind, which should be noted.

Of course, all file / folder names that are not bold can be customized.

We create a new folder "code" somewhere on the computer for programming; Create a new folder "cpp" in the "code" folder for C + + programming.

Select "file" - "add folder to workspace..." in "VSCode" to add the "cpp" folder. After that, we can save the workspace through "file" - "save workspace as..." for subsequent use and separate configuration and installation of plug-ins.

Next, we create new folders according to our needs, such as:

I plan to create a new "practice" folder for learning examples and exercises in the book, and then subdivide the folder according to the book name and directory in "practice".

At the same time, create a "gsl" folder to store the lightweight library used by "Cpp Core Guidelines" GSL: Guidelines support library ——A library that contains only header files without links.

(to illustrate, it happens that this library cannot be downloaded in MSYS2. You can also download it and put the "gsl" folder in the "MSYS2 installation path \ clang64\include" as the "system header file")

Next, let's consider one thing: how to compile links and debug code?

Although CMake will be used to manage the entire workspace next, I do not intend to use CMake to compile link code (which is also a very simple problem once I get started). CMake is only used to support the framework and provide "compile" for Clangd_ Commands. JSON "to analyze multi file projects.

If you want to learn how to compile and link through CMake, please browse the last -7- reference after reading this article.

We create a new folder ". vscode" in the root directory, and create files with the full name of "tasks.json" (task) and "launch.json" (debugging configuration).

As always, I will attach the code and corresponding comments. If you want to really understand it, you need to read more information.

tasks.json:

Additionally, for gsl library, add "- I${workspaceFolder}\gsl" (- uppercase i)(include) in the parameter

Since the gsl library only has header files, there is no need to add "- lgsl" (- lowercase L)(link) to the parameters to link

{
  "tasks": [
    {
      "type": "shell",
      "label": "Clang++: Compile single file",
      // Compiler path
      "command": "C:\\msys64\\clang64\\bin\\clang++.exe",
      // The parameters attached to the compiler are reflected in the terminal, that is, "clang+ arg1 arg2 arg3..."
      "args": [
        // Compiled file
        "${fileDirname}\\${fileBasenameNoExtension}.cc",
        // The generated file is debug.exe
        "-o",
        "debug.exe",
        // Enable debugging
        "-g",
        // Enable all diagnostics, but may not compile due to some innocuous problems
        // Compared with - Weverything, this is the recommended method in the Clang compiler user's manual
        "-Wall",
        "-Wextra",
        // Multithreading support
        "-pthread",
        // Use LLVM lld linker instead of default linker
        "-fuse-ld=lld",
        // Enable debug information optimization
        "-fstandalone-debug",
        // Diagnostic information coloring
        "-fcolor-diagnostics",
        // Analyze all comments (in fact, just tell Clangd, that is, add them to compile_commands.json)
        // By default, Clang only analyzes Doxygen style comments ("/ * *", "/ /")
        "-fparse-all-comments",
        // Set the standard library of C + + to libc + +: the standard library corresponding to clang
        "-stdlib=libc++",
        // Set the C + + version to c++20
        "-std=c++20",
        // Generate code for a given environment
        "--target=x86_64-w64-mingw"
      ],
      "options": {
        // The startup path of Clang, so debug.exe will be output in the root directory of the workspace
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": ["$gcc"],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "presentation": {
        "echo": true,
        // Whether to jump to the terminal panel during task execution can be always, silent, never. Please refer to the VSC documentation for details. Even if it is set to never, you can still see it manually
        "reveal": "always", 
        // When set to true, the focus of task execution can be focused on the terminal, but for compiling C/C + +, setting to true makes no sense
        "focus": false, 
        // The compilation information of different files shares a terminal panel
        "panel": "shared" 
      },
      "detail": "Clang++: Compile a single file"
    },
    {
      "type": "shell",
      "label": "Clang++: Compile multiple files",
      "command": "C:\\msys64\\clang64\\bin\\clang++.exe",
      "args": [
        // '*' is a wildcard
        "${fileDirname}\\*.cc",
        "-o",
        "debug.exe",
        "-g",
        "-Wall",
        "-Wextra",
        "-pthread",
        "-fuse-ld=lld",
        "-fstandalone-debug",
        "-fcolor-diagnostics",
        "-fparse-all-comments",
        "-stdlib=libc++",
        "-std=c++20",
        "--target=x86_64-w64-mingw"
      ],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": ["$gcc"],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
      },
      "detail": "Clang++: Compile all files in the directory where the current file is located"
    }
  ],
  "version": "2.0.0"
}

launch.json:

{
  // 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": "LLDB: Generate and debug order files",
      "type": "lldb",
      "request": "launch",
      "program": "${workspaceFolder}\\debug",
      "args": [],
      "stopOnEntry": false,
      "cwd": "${workspaceFolder}",
      "internalConsoleOptions": "neverOpen",
      "environment": [],
      "externalConsole": false,
      "preLaunchTask": "Clang++: Compile single file"
    },
    {
      "name": "LLDB: Generate and debug multiple files",
      "type": "lldb",
      "request": "launch",
      "program": "${workspaceFolder}\\debug",
      "args": [],
      "stopOnEntry": false,
      "cwd": "${workspaceFolder}",
      "internalConsoleOptions": "neverOpen",
      "environment": [],
      "externalConsole": false,
      "preLaunchTask": "Clang++: Compile multiple files"
    },
    {
      "name": "LLDB: Debug compiled debug.exe",
      "type": "lldb",
      "request": "launch",
      "program": "${workspaceFolder}\\debug",
      "args": [],
      "stopOnEntry": false,
      "cwd": "${workspaceFolder}",
      "internalConsoleOptions": "neverOpen",
      "environment": [],
      "externalConsole": false,
    }
  ]
}

After configuration, you can click "terminal" - "run generation task..." or Ctrl + Shift + B to run the task. This is the same as the comments. Compile the file you open and output it as the file in the root directory of the workspace   debug.exe.

After that (or you can do it at the same time), you can click "run" - "start debugging" or F5 to debug. To change the debugging configuration, click "run and debug" on the left to change it at the top of the sidebar.

Please refer to for more parameters Visual Studio Code Variables Reference and   Clang compiler user manual.

② Support frame with CMake

In my understanding, "CMake" configuration is completed by adding a file named "CMakeLists.txt" in each directory and defining the information of the folder in the file. All information will be analyzed and stored in the "build" folder, and a "compile" for the compiler to analyze the file structure will be generated_ commands.json」.

What we're going to do in this section is to get it with the help of CMake   compile_commands.json to let Clangd play its full role.

We first create a new file like this in the root directory of the workspace and save the following contents. In CMakeLists.txt, comments begin with "#".

#CMake minimum version required
cmake_minimum_required(VERSION 3.0.0)
#Project name (the project name must be set in the root directory, and the files with the same project name will be regarded as the same project)
project(cpp)

#Add a build outside the source and add the search path of include (similar to adding a header file search path in C + +)
set(CMAKE_MODULE_PATH
    ${CMAKE_MODULE_PATH}
    ${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules
    )
#add to basicEnv Contents of the file (similar to C++ Medium #include)
include(basic_env)

#Add the subdirectory practice. CMakeLists.txt should also be created in the subdirectory
#Since the gsl directory contains only header files and no source files, we do not need to add them
add_subdirectory(practice)

As required in line 6-9, we create a new folder "cmake" under the root directory of the workspace_ Modules, in which the full name is "basic"_ Env. Cmake ", where we add compiler parameters like" tags. JSON ".

set(CMAKE_CXX_FLAGS
    "${CMAKE_CXX_FLAGS}
    -g
    -pthread
    -fuse-ld=lld
    -fstandalone-debug
    -Wall
    -Wextra
    -fcolor-diagnostics
    -fparse-all-comments
    -stdlib=libc++
    -std=c++20
    --target=x86_64-w64-mingw"
    )

Enter the "practice" folder. Whenever we enter a folder, we ask ourselves:

Do the contents in this folder belong to the same project?

Obviously, the "practice" folder is used to contain our reading subdirectories and is not counted as a project.

But based on the content "add" of the root directory "CMakeLists.txt"_ Subdirectory (practice) ", we still want to create a new" CMakeLists.txt "for it.

As mentioned earlier, "practice" is not a project, and we don't need to give it a project name. In "CMakeLists.txt", the only thing we need to do is through "add"_ Add subdirectory (folder name) to CMake framework.

We have reached the conceptual "project directory".

If it is a real project, we may need to go deep into each directory and add "CMakeLists.txt" one by one.

But we just want to get "compile"_ Commands. JSON ", and the example and exercise codes of one book and another are unlikely to interact. Therefore, we simply add "CMakeLists.txt" under the root directory of "project directory" and require:

  • This is a project
  • All source files in the directory (here is the source file with. cc suffix) will be compiled into the execution file of the project
  • All header files in the directory may be included

For example, for "C"++_ primer_ Add project directory. I require its project name to be "C"++_ primer_ plus」:

#Project name
project(c++_primer_plus)

#Add all source files with. cc suffix to the variable src
#If you need. cpp as the suffix, you can imitate this format, but the variable cannot be repeated
file(GLOB_RECURSE src "${CMAKE_CURRENT_SOURCE_DIR}/*.cc")

#Add the possible path of the header file (the system header file determines the path when Clangd knows what the compiler is)
include_directories(
    #gsl Library in the root directory
    ${CMAKE_SOURCE_DIR}/gsl
    #Project catalogue
    ${CMAKE_SOURCE_DIR}/practice/c++_primer_plus
)

#Take the file corresponding to src as part of the source file for the final executable
#add_ Executable (project name parameter 1 Parameter 2...)
#Variables need to be referenced in the form of ${variable name}
add_executable(c++_primer_plus ${src})

If you want to be lazy, you can also configure these contents in "CMakeLists.txt" under the "practice" folder.

But it may be more troublesome.

Close "VS Code" and reopen the workspace. CMake will automatically search the compiler and configure the entire workspace.

If not found, Ctrl + Shift + P opens the command menu, searches "CMake", selects "CMake: edit user's local CMake toolkit", and adds / replaces the following information: (the compiler path should be changed to MSYS2 installation path)

[
  {
    "name": "Clang 12.0.1 x86_64-w64-windows-gnu",
    "compilers": {
      "C": "C:\\msys64\\Clang64\\bin\\clang.exe",
      "CXX": "C:\\msys64\\Clang64\\bin\\clang++.exe"
    }
  }
]

Since I disabled CMake auto configuration on save (you can also open it) in the settings, when we need to update the configuration, Ctrl + Shift + P opens the command menu, searches "CMake" and selects "CMake: configuration".

In addition, don't forget to search "Cland" and select "Cland: restart language server" to let Clangd read the new configuration.

If you want to learn how to compile and link through CMake, please browse the last -7- reference after reading this article.

③ Implementing version management with Git

What is version management? For the time being, you can think that version management is backing up every modification. If any modification is not satisfactory, you can easily recover from it. Of course, version management is much more than that.

Let Git ignore files / folders

From the section supporting the framework with CMake, we already know that the ". Cache" folder is used to cache the information analyzed by Clangd. Whenever we start "VSCode" or manually "configure" through the command menu, the "build" folder will be updated based on other files—— There is no need to back up these two folders at all.

So we create a new file with the full name ". gitignore" in the root directory of the workspace. Add:

/.cache/
/build/

For more information about. gitignore, refer to .gitignore

Configure our Git

First, let Git know us.

Create a new terminal (refer to - 4 - other common shortcut keys), and type the following:

git config --global user.name "Your nickname"
git config --global user.email "Your mailbox"

Click source control - initialize repository on the left.

You now have a near professional C + + workspace.

-4 - Common shortcut keys

The less we switch from keyboard to mouse, the more efficient we are.

Here are some shortcuts that I have been able to use skillfully (for more, please refer to VSCode shortcut key Or file - preferences - keyboard shortcuts):

Insert row

  • Ctrl + Enter: inserts a row below the row
  • Ctrl + Shift + Enter: inserts a row above the row

Line operation (can be used with multi cursor and selection)

  • Ctrl + Shift + K: delete row
  • Alt + ↑ / ↓: move line
  • Shift + Alt + ↑ / ↓: copy lines

Multi cursor and selection

  • Shift + ← / →: word selection
  • Ctrl + Shift + ← / →: word selection
  • Shift + Alt +   ← / →: reduce / expand selection
  • Ctrl + Alt + ↑ / ↓: add cursor above / below (adding cannot be undone)
  • Ctrl + Shift + Alt +   ↑ / ↓ / ← / →: block selection (cursor can also be added and cancelled, and the selection will not jump to the next line after the end of the line)
  • Shift + Alt + i: add a cursor at the end of each row in the selection area

other

  • Ctrl + S: save current file
  • Ctrl + Shift + P: opens the command menu
  • Ctrl + B: toggles the visibility of the sidebar
  • Ctrl + Shift + B: run build task
  • CTRL + ` (the key above the tab): switch the visibility of the terminal (if there is no terminal, a new one will be created)
  • F5: debug with current configuration
  • F12: go to definition
  • Ctrl + ↑ / ↓: scroll up / down editor
  • Ctrl + F/H: search / replace
  • Hold down Ctrl and click the left mouse button: go to the definition and jump to the corresponding file
  • ......

-5 - (optional) VSCode plug-in I use

Please refer to quick installation of the plug-ins I recommend for usage

Universal plug-in

{
  "recommendations": [
    "ms-vscode.azure-account",
    "ms-azuretools.vscode-azureappservice",
    "ms-azuretools.vscode-azureresourcegroups",
    "hookyqr.beautify",
    "aaron-bond.better-comments",
    "samuelcolvin.jinjahtml",
    "auchenberg.vscode-browser-preview",
    "ms-ceintl.vscode-language-pack-zh-hans",
    "formulahendry.code-runner",
    "adpyke.codesnap",
    "bierner.color-info",
    "randomfractalsinc.vscode-data-preview",
    "hediet.debug-visualizer",
    "ms-azuretools.vscode-docker",
    "cschlosser.doxdocgen",
    "editorconfig.editorconfig",
    "redvanworkshop.explorer-exclude-vscode-extension",
    "mkxml.vscode-filesize",
    "mhutchie.git-graph",
    "github.vscode-pull-request-github",
    "eamodio.gitlens",
    "spywhere.guides",
    "kisstkondoros.vscode-gutter-preview",
    "wix.vscode-import-cost",
    "oderwat.indent-rainbow",
    "ms-toolsai.jupyter",
    "leetcode.vscode-leetcode",
    "ritwickdey.liveserver",
    "yzhang.markdown-all-in-one",
    "webfreak.debug",
    "eg2.vscode-npm-script",
    "christian-kohler.npm-intellisense",
    "techer.open-in-browser",
    "ibm.output-colorizer",
    "quicktype.quicktype",
    "christian-kohler.path-intellisense",
    "johnpapa.vscode-peacock",
    "esbenp.prettier-vscode",
    "chrmarti.regex",
    "humao.rest-client",
    "shan.code-settings-sync",
    "tyriar.sort-lines",
    "jkjustjoshing.vscode-text-pastry",
    "wayou.vscode-todo-highlight",
    "gruntfuggly.todo-tree",
    "chakrounanas.turbo-console-log",
    "octref.vetur",
    "visualstudioexptteam.vscodeintellicode",
    "deerawan.vscode-faker",
    "mikey.vscode-fileheader",
    "vscode-icons-team.vscode-icons",
    "jaspernorth.vscode-pigments",
    "wasteamaccount.webtemplatestudio-dev-nightly",
    "redhat.vscode-yaml",
    "appulate.filewatcher",
    "dbaeumer.vscode-eslint",
    "vadimcn.vscode-lldb",
    "codeinchinese.englishchinesedictionary",
    "alefragnani.bookmarks",
    "hbybyyang.gitee-vscode-plugin",
    "bbenoist.doxygen",
    "jbockle.jbockle-format-files",
    "njpwerner.autodocstring",
    "richie5um2.vscode-sort-json"
  ]
}

C + + plug-in

{
	"recommendations": [
    "jeff-hykin.better-cpp-syntax",
    "danielpinto8zz6.c-cpp-project-generator",
    "twxs.cmake",
    "ms-vscode.cmake-tools",
    "guyutongxue.cpp-reference",
    "llvm-vs-code-extensions.vscode-clangd",
    "ms-vscode.cpptools"
  ]
}

-6 - (optional) VSCode configuration I use

Please refer to the configuration file for the usage method

Note: the path of Clangd is not given in the configuration. Please copy and paste the relevant configuration yourself.

{
/**********
 * VSCode *
 **********/
  // Controls when the internal debugging console opens
  "debug.internalConsoleOptions": "neverOpen",
  // The Enter key is not allowed to process input suggestions to avoid ambiguity between line feed and acceptance of suggestions
  // You can also allow this item to wrap using Ctrl + Enter
  "editor.acceptSuggestionOnEnter": "off",
  // The control editor should automatically overwrite the opening or closing quotation marks
  "editor.autoClosingOvertype": "always",
  // Disable automatic detection of file indent mode and indent size, that is, automatically change the file to the indent format configured by VSCode after opening the file
  "editor.detectIndentation": false,
  // Format file when pasting
  "editor.formatOnPaste": true,
  // Format file on save
  "editor.formatOnSave": true,
  // Automatically display inline suggestions in the editor
  "editor.inlineSuggest.enabled": true,
  // Whether to display a small panel with parameter document and type information when entering
  "editor.parameterHints.enabled": true,
  // Controls whether suggestions are automatically displayed as you type code
  "editor.quickSuggestions": {
    // Not allowed when typing comments
    "comments": false,
    // Not allowed when typing string
    "strings": false,
    // Allow when typing other
    "other": true
  },
  // Controls the wait time (in milliseconds) before quick suggestions are displayed
  "editor.quickSuggestionsDelay": 0,
  // Show indented guides. Because I use the plug-in, the display of built-in guides is turned off here
  "editor.renderIndentGuides": false,
  // Controls how the editor displays symbols on white space characters
  "editor.renderWhitespace": "none",
  // Code snippets are recommended over other suggestions
  "editor.snippetSuggestions": "top",
  // Simulate the behavior of tabs when using space indentation to facilitate alignment
  "editor.stickyTabStops": true,
  // Controls whether words close to the cursor are prioritized when sorting
  "editor.suggest.localityBonus": true,
  "editor.suggest.shareSuggestSelections": true,
  // Controls whether suggestions are automatically displayed after the trigger character is typed
  "editor.suggestOnTriggerCharacters": true,
  // One tab = 2 spaces
  "editor.tabSize": 2,
  // Controls whether a list of suggestions is provided based on the text in the document
  "editor.wordBasedSuggestions": true,
  // There is no need to confirm when deleting files
  "explorer.confirmDelete": false,
  // No confirmation is required when moving files
  "explorer.confirmDragAndDrop": false,
  // Rename method when pasting a file with the same name
  // smart: intelligently add / increment numbers at the end of duplicate names
  "explorer.incrementalNaming": "smart",
  // Ignore notification of extension suggestions
  "extensions.ignoreRecommendations": true,
  // Auto save unsaved editor: after waiting time
  "files.autoSave": "afterDelay",
  // Wait time for auto save (MS)
  "files.autoSaveDelay": 1000,
  // Configure glob mode for excluded files and folders
  // Based on this setting, file explorer determines which files and folders to show or hide
  "files.exclude": {
    "**/.classpath": true,
    "**/.factorypath": true,
    "**/.project": true,
    "**/.settings": true
  },
  // Remember unsaved files between sessions to allow you to skip the save prompt when you exit the editor
  // onExitAndWindowClose: on exit or window close
  "files.hotExit": "onExitAndWindowClose",
  // Grunt task automatic detection
  "grunt.autoDetect": "on",
  // Gulp task automatic detection
  "gulp.autoDetect": "on",
  // Where should the cell toolbar be displayed, or do you want to hide it
  "notebook.cellToolbarLocation": {
    // Default: right
    "default": "right",
    // Jupiter Notebook: left
    "jupyter-notebook": "left"
  },
  // Configure glob mode for files and folders excluded from search
  "search.exclude": {
    // "someFolder/": true,
    // "somefile": true
  },
  // Displays the line number of the search results
  "search.showLineNumbers": true,
  // When the search term is lowercase, the search is case insensitive
  // Otherwise, it is case sensitive
  "search.smartCase": true,
  // The integrated terminal defaults to PowerShell
  "terminal.integrated.defaultProfile.windows": "PowerShell",
  // Enable visual ringing tone for integrated terminal
  "terminal.integrated.enableBell": true,
  // Integrated terminal code: zh_CN.UTF-8
  "terminal.integrated.env.windows": {
    "LC_ALL": "zh_CN.UTF-8"
  },
  // The integrated terminal uses GPU acceleration
  "terminal.integrated.gpuAcceleration": "on",
  // When the integration terminal right clicks, select the word below the cursor and open the context menu
  "terminal.integrated.rightClickBehavior": "selectWord",
  // Window zoom level: 1 (original level is 0)
  "window.zoomLevel": 1,
  // File icon theme: plug in vscode icons
  "workbench.iconTheme": "vscode-icons",
  // Do not open the editor at startup without recovering information from the previous session
  "workbench.startupEditor": "none",
  // Displays the action items for the view header
  "workbench.view.alwaysShowHeaderActions": true,

/********
 * Font *
 ********/
  // Font family: Fira Code
  "editor.fontFamily": "Fira Code",
  // CodeLens font family: Fira Code
  "editor.codeLensFontFamily": "Fira Code",
  // Enable hyphenation
  "editor.fontLigatures": true,
  // font size
  "editor.fontSize": 16,
  // Integrated terminal font size
  "terminal.integrated.fontSize": 14,
  // output window
  "[Log]": {
    // font size
    "editor.fontSize": 15
  },

/*********
 * Color *
 *********/
  // Controls whether brackets are shaded
  "editor.bracketPairColorization.enabled": true,
  // I got used to the blue brackets in the Bracket Pair Colorizer 2, so I changed the color of the blue brackets in VSCode
  "workbench.colorCustomizations": {
    "[Default Dark+]": {
      "editorBracketHighlight.foreground3": "#9CDCFE"
    }
  },
  // Semantic highlighting
  "editor.semanticHighlighting.enabled": true,
  // Semantic highlight customization
  "editor.semanticTokenColorCustomizations": {
    "enabled": true,
    "rules": {
      // Static quantity (static variable, static function)
      "*.static": {
        "fontStyle": "italic"
      },
      // macro
      "macro": {
        "foreground": "#8f5daf"
      },
      // Member function
      "method": {
        "fontStyle": "underline"
      },
      // Namespace
      "namespace": {
        "foreground": "#00d780"
      },
      // Function parameters
      "parameter": {
        "foreground": "#C8ECFF"
      },
      // Member variables seem to need more than cland12
      "property": {
        "fontStyle": "underline",
        "foreground": "#C8ECFF"
      },
      // Type parameter
      "typeParameter": {
        "foreground": "#31A567"
      },
      // Read only quantities are equivalent to macros
      "variable.readonly": {
        "foreground": "#8f5daf"
      }
    }
  },

/*******
 * Git *
 *******/
  // Automatically extract submissions from the default remote library of the current Git repository
  "git.autofetch": true,
  // Confirm before synchronizing Git repository
  "git.confirmSync": false,
  // When there are no pending changes, commit all changes directly
  "git.enableSmartCommit": true,

/**********
 * Clangd *
 **********/
  // Clangd path
  // Turn off IntelliSenseEngine provided by C/C + +
  "C_Cpp.intelliSenseEngine": "Disabled",
  // Clangd operation parameters (enter clangd -- help list hidden on the terminal / command line to view more)
  "clangd.arguments": [
    // Let Clangd generate more detailed logs
    "--log=verbose",
    // The output JSON file is more beautiful
    "--pretty",
    // Global completion (the pop-up suggestions during input will provide possible symbols in all files configured in CMakeLists.txt, and the header file will be automatically supplemented)
    "--all-scopes-completion",
    // More detailed completion
    "--completion-style=detailed",
    // Allow supplementary header files
    "--header-insertion=iwyu",
    // In input suggestions, items that contain header files are distinguished by dots from items that do not yet contain header files
    "--header-insertion-decorators",
    // Automatically analyze files in the background (based on complie)_ Commands, which we generate with CMake)
    "--background-index",
    // Enable clang tidy to provide static checking
    "--clang-tidy",
    // The parameter of clang tidy static check indicates which rules are followed for static check. For details, see "advantages over VSCode configured according to official documents"
    // The * after the parameter indicates a wildcard
    // Adding - such as - modernize use trailing return type before the parameter will disable a rule
    "--clang-tidy-checks=cppcoreguidelines-*,performance-*,bugprone-*,portability-*,modernize-*,google-*",
    // Default formatting style: Google open source project code Guide
    "--fallback-style=Google",
    // Number of tasks opened at the same time
    "-j=12",
    // pch optimized location (memory or disk, selecting memory will increase memory overhead, but will improve performance)
    "--pch-storage=memory",
    // After adding this item, placeholders will be provided for the parameters when completing the function. After typing, press Tab to switch to the next placeholder or even the end of the function
    "--function-arg-placeholders",
    // compelie_ Directory location of the commands.json file (relative to the workspace, the file generated by CMake is in the build folder by default, so it is set to build)
    "--compile-commands-dir=build"
  ],
  // Automatically detect Cland updates
  "clangd.checkUpdates": true,
  // Cland's snippets have many jump points. Without this, Intellisense must be triggered manually
  "editor.suggest.snippetsPreventQuickSuggestions": false,

/*********
 * CMake *
 *********/
  // When you save the contents of cmake.sourceDirectory or CMakeLists.txt, the CMake project directory is not automatically configured
  "cmake.configureOnEdit": false,
  // Automatically configure the CMake project directory when it is opened
  "cmake.configureOnOpen": true,
  // After successful configuration, compile will be_ Copy commands.json to this location
  "cmake.copyCompileCommands": "",

/********
   * LLDB *
   ********/
  // LLDB instruction auto completion
  "lldb.commandCompletions": true,
  // The LLDB pointer displays the dereference content
  "lldb.dereferencePointers": true,
  // LLDB previews the variable value when the mouse hovers over the variable
  "lldb.evaluateForHovers": true,
  // LLDB does not display assembly code
  "lldb.showDisassembly": "never",
  // LLDB generates more detailed logs
  "lldb.verboseLogging": true,

/**************
 * Extensions *
 **************/
  // Code Runner execute command
  "code-runner.executorMap": {
    "c": "cd $dir && clang -g -g -pthread -fuse-ld=lld -fstandalone-debug -Wall -fcolor-diagnostics -fparse-all-comments -stdlib=libc -std=c17 --target=x86_64-w64-mingw $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
    "cpp": "cd $dir && clang++ -g -pthread -fuse-ld=lld -fstandalone-debug -Wall -fcolor-diagnostics -fparse-all-comments -stdlib=libc++ -std=c++20 --target=x86_64-w64-mingw $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
  },
  // Code Runner runs in the terminal
  "code-runner.runInTerminal": true,
  // doxygen uses the user mailbox configured in Git
  "doxdocgen.generic.useGitUserEmail": true,
  // doxygen uses the user name configured in Git
  "doxdocgen.generic.useGitUserName": true,
  // Indent rainbow update wait time (MS)
  "indentRainbow.updateDelay": 0,
  // Indent rainbow ignore error
  "indentRainbow.ignoreErrorLanguages": [
    "markdown"
  ],
  // Jack task auto detection
  "jake.autoDetect": "on",
  // Force buckle default language: C++
  "leetcode.defaultLanguage": "cpp",
  // Force buckle terminal: Chinese version
  "leetcode.endpoint": "leetcode-cn",
  // Authorization to upload usage data and errors to the Red Hat server
  "redhat.telemetry.enabled": true,
  // Allow scanning of hidden files and files starting with a period
  "todo-tree.filtering.includeHiddenFiles": true,
  // Configure glob mode to editor
  "workbench.editorAssociations": {
    // Associate *. ipynb files to jupyter notebook
    "*.ipynb": "jupyter-notebook"
  },
}

-7 - Reference

Tags: C++ cmake git Visual Studio Code CLang

Posted on Mon, 06 Sep 2021 23:53:54 -0400 by jimmyp3016