Introduction#
Due to some reckless operations, I messed up my previous Ubuntu installation. Taking this opportunity, I switched the distribution of my WSL to Arch, and I also plan to use the LLVM toolchain in VSCode.
Installing Arch is very convenient, you can follow the instructions in How to Setup | ArchWSL official documentation (wsldl-pg.github.io) and get it done within 10 minutes.
However, using the LLVM toolchain in VSCode is not very convenient. I searched online for many tutorials, most of which require a project (such as CMake) to work with. But if you're just a college student doing homework, it's actually easier to use F5 directly.
The main steps are to use clang/lldb for compilation and debugging, and to use clangd for autocompletion and checking. These two steps should be independent of each other and you can choose to use only one of them. However, most of the tutorials I found seem to mix them together.
My environment:
Windows 11, Arch Linux on WSL2
Environment that I think should work:
Any version of Windows that can install WSL
Using clang/lldb for single file compilation and debugging#
-
Make sure that
clang++
andlibc++
are correctly installed.- Check with
clang++ -version
andpacman -Qq|grep libc++
. - If they are not installed,
clang++
is included in theclang
package, so you can useyay -S clang
if you use yay to manage AUR. The same goes forlibc++
.
- Check with
-
Make sure that the CodeLLDB plugin is enabled in VSCode (if there is an error downloading, you can download it manually using the URL provided in the error message and install it manually).
-
Create a tasks.json file and place it in the .vscode folder.
{ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "type": "shell", "label": "clang++ build", "command": "clang++", "args": [ "-std=c++17", "-stdlib=libc++", "-g", "${file}", "-fstandalone-debug", //to enable viewing std::string etc. when using lldb "-o", "${fileDirname}/build/${fileBasenameNoExtension}" ], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": ["$msCompile"], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ] }
- This tasks.json file is taken from the VSCode documentation, specifically Configure VS Code for Clang/LLVM on macOS (visualstudio.com), with some modifications for Linux.
- My preference is to put all executable files in the
./build/
folder. If you don't do this, you need to change the file paths in steps 3 and 4, and skip step 5.
-
Create a launch.json file and place it in the .vscode folder.
{ // 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": [ { "preLaunchTask": "clang++ build", "type": "lldb", "request": "launch", "name": "Debug", "program": "${workspaceFolder}/build/${fileBasenameNoExtension}", "args": [], "cwd": "${workspaceFolder}" } ] }
-
Create a build folder in the workspace folder (otherwise, there will be an error!!!).
-
Press F5 to run the program.
Using clangd for autocompletion and code checking#
- Make sure that clangd is installed (it should be included in the same package as clang++).
- Install the clangd extension in VSCode.
- Enter
which clangd
in the terminal and note down the file directory. - Create a settings.json file and place it in the .vscode folder.
{
// Some settings for clangd, you can refer to the official documentation [Configuration (llvm.org)](https://clangd.llvm.org/config)
"clangd.arguments": [
"--background-index",
"--compile-commands-dir=${workspaceFolder}/build",
"-j=32",
"--folding-ranges",
"--query-driver=/usr/sbin/clang++",
"--clang-tidy",
"--clang-tidy-checks=performance-*,bugprone-*",
"--all-scopes-completion",
"--header-insertion=iwyu",
"--completion-style=detailed",
"--function-arg-placeholders",
"--header-insertion=iwyu",
"--pch-storage=memory",
"--pretty"
],
"clangd.path": "/usr/sbin/clangd",//the dir get from step 3
// The following two settings are for speeding up autocomplete
"editor.quickSuggestionsDelay": 3,
"editor.suggest.snippetsPreventQuickSuggestions": false
}
About the .clang-format file#
My preference is to put it directly under ~
(if your code is all under your ~
and its subfolders).
To generate it, the official website is too ugly, so I directly configure it in CLion and export it as .clang-format, which is both visual and convenient.
Here is my .clang-format file:
# Generated from CLion C/C++ Code Style settings
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: None
AlignOperands: Align
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Always
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterReturnType: None
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: true
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
ColumnLimit: 0
CompactNamespaces: false
ContinuationIndentWidth: 8
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PointerAlignment: Right
ReflowComments: false
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 0
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Never
Troubleshooting#
clangd server keeps crashing#
- Solution: Do not add the
--folding-ranges
parameter.- If you add it, the server will crash when analyzing the source code related to
std::vector
, even if your code does not usestd::vector
. The reason will be analyzed later.
- If you add it, the server will crash when analyzing the source code related to
VSCode cannot connect to the internet correctly in WSL#
- The main reason is that VSCode in WSL uses the proxy IP+port from Windows (usually
127.0.0.1:port
). Therefore, we need to set thehttp_proxy
andhttps_proxy
for WSL, replacing127.0.0.1
with the IP of your Windows in the local network.