Getting Started with C++ and Visual Studio Code on Windows
Before going through these steps make sure you have done Setup C++ development environment on Windows
Visual Studio Code
Download and install from Visual Studio Code site.
Open Visual Studio Code and press Cmd + Shift + P
. Select Shell Command: Install 'code' command in PATH
.
C++ Project
Create a directory called simple in ~/cpp/simple
Add a configuration script configure.ps1
:
$temp_file = [IO.Path]::GetTempFileName()
# find where Visual Studio 2022 is installed
$vs_install_dir = $(Get-VSSetupInstance | Select-VSSetupInstance -Version '[17.0,18.0]' | Select-Object -ExpandProperty InstallationPath)
$vs_common_tools = "${vs_install_dir}/Common7/Tools/"
# run `VsDevCmd.bat -arch=amd64 -host_arch=amd64` and save environment to $temp_file
cmd /c " `"$vs_common_tools/VsDevCmd.bat`" -arch=amd64 -host_arch=amd64 && set > `"$temp_file`""
# copy the environment variables into PowerShell
Get-Content $temp_file | Foreach-Object {
if($_ -match "^(.*?)=(.*)$") {
Set-Content "env:\$($matches[1])" $matches[2]
}
}
Remove-Item $temp_file
Open the directory in Visual Studio Code. It is important to source the configure.ps1
script before running code .
in order to setup the correct C++ environment:
Install the C/C++ Extension Pack.
Project Files
Add the following files:
src/main.cpp
CMakeLists.txt
build.ps1
New-Item -Force -Path ./build/debug -ItemType Directory
Push-Location ./build/debug
cmake -G 'Ninja' -DCMAKE_BUILD_TYPE=debug ../..
ninja
Pop-Location
.gitignore
Test the build
Open Terminal in Visual Studio Code and test the build from command line:
Automate the build
Add the following Visual Studio Code specific files to the .vscode
subdir:
.vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"type": "shell",
"windows": {
"command": "${workspaceFolder}/build.ps1",
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Test the build by pressing Ctrl + Shift + B
. Visual Studio Code should execute the build.ps1
script automatically.
Setup Debugging
Add the following Visual Studio Code specific files to the .vscode
subdir:
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug (cppvsdbg)",
"type": "cppdbg",
"request": "launch",
"cwd": "${workspaceFolder}",
"windows": {
"type": "cppvsdbg",
"program": "${workspaceFolder}/build/debug/simple.exe"
},
"preLaunchTask": "Build"
}
]
}
Test the debugging
Set a breakpoint on the first line of int main()
inside src/main.cpp
. Press F5
to launch the debugger. It should stop at the breakpoint.