Setting up VS Code

Focus on Python and C++ Programming

Introduction
General set up
├─ Install
├─ Configuration
├─ Basic shorcuts
└─ Run and debug
Python in VS Code
C++ in VS Code
Conclusion
References
Appendix


Introduction

VS Code, developed by Microsoft, has emerged as a game-changing code editor, revered for its lightweight design and extensive capabilities. In this post, we introduce VS Code, focusing on its general setup, configuration, and practical usage for both Python and C++ development.

General set up

Install

To install VS Code, we need to download .deb file from code.visualstudio.com and then:

1
2
3
4
sudo dpkg -i <file.deb>
sudo apt-get install -f # Install dependencies

# sudo apt install <file.deb>

Alternatively, we can use VSCodium which is a freely-licensed binary distribution of Microsoft’s editor VS Code.

1
snap install codium --classic

Configuration

For VS Code extensions, I exported mine (C, C++, cmake, python, docker, doxygen, git, jupyter, latex, markdown, ssh, code completion, code formatting, dark theme, etc.) as follows:

1
code --list-extensions | xargs -L 1 echo code --install-extension > my_vscode_extensions.sh

And we can then import it by:

1
2
wget https://maiminh1996.github.io/scripts/my_vscode_extensions.sh
bash my_vscode_extensions.sh

Three important configuration files in VS Code that allow to customize various aspects of the project’s environment and settings are: launch.json, settings.json, and tasks.json.

  • .vscode/launch.json: used to configure the debugger. It contains settings for launching and debugging, such as specifying which file to launch, the runtime arguments to pass, the environment variables to set, and more.
  • .vscode/settings.json: used to configure various settings, such as editor preferences, language-specific settings, and extensions. Check out my_settings.json.
  • .vscode/tasks.json: used to define tasks that can be run from within VS Code, such as building the code, running tests, or deploying the project. It contains settings for running shell commands, configuring arguments, and more.

Basic shorcuts

  • File navigation: Ctrl+P
  • Opened file navigation: Ctrl+Tab, hold Ctrl + Up/ Down
  • Opened folder navigation: Ctrl+R
  • Command Palette: Ctrl+Shift+P/ F1
  • Format Document: Ctrl+Shift+I
  • Refactor: Ctrl+Shift+R
  • IntelliSense: Ctrl+Space

Run and debug

Set up launch.json to run/ debug (menu bar):

  • Run without Debugging (Ctrl+F5)
  • Start Debugging (F5)
    • Continue / Pause (F5)
    • Step Over (F10)
    • Step Into (F11)
    • Step Out (Shift+F11)
    • Restart (Ctrl+Shift+F5)
    • Stop (Shift+F5)

Add Conditional breakpoints:

  • Expression condition
  • Hit count
  • Log message

Run & Debug (activity bar) Ctrl+Shift+D:

  • Variables: to see all local and global variables
  • Watch: to monitor specific variables or expressions as they change during the course of the program’s execution
  • Call stack: the function on which the program is running
  • Breakpoints: to see all breakpoints in the project

Panel (Ctrl+J):

  • Terminal: fully-featured terminal emulator within VS Code.
  • Problems: to see bugs when run/ debug a program
  • Debug console: to display output from the program being debugged/ interacting with the program being debugged

Python in VS Code

We have a python project as below and we want to run/ debug in VS Code.

1
2
3
4
5
6
7
8
9
$ tree
├── src
│   ├── main.py
│   └── ...
├── ...
│   ├── ...
│   └── ...
└── .vscode
    └── launch.json

Run & Debug: add the configuration following to launch.json to run/ debug src/main.py file. See more launch attributes here: launchjson-attributes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python project", // Set project's name
            "type": "python", // Python launch configuration.
            /* Set config process */
            "request":  "launch",       // launch in a new process.
                        // "attach",    // attach into an existing process 
                        // "core",      // debugging core dumps on Unix-like systems.
                        // "remote",    // remote machine.
                        // "test",      // running tests in a test framework.
            /* Set a specific file to be launched */
            "program":  "main.py", // check "cwd".
                        // "${file}", // check "cwd".
                        // "${workspaceFolder}/main.py", // no need to care about "cwd"
                        // "path/to/program", // absolute path. no need to care about "cwd"
            /* Set the python path instead of setting in status bar */
            // "pythonPath": "/usr/local/bin/python3.9",
            /* Set environment variables */
            "env": { 
                "MY_ENV_VAR": "my_value",
                "PATH": "${env:PATH}:new_path" // concatenate a new path
            },
            /* Debugger console */
            "console":  "integratedTerminal", 
                        // "internalConsole",
                        // "externalTerminal",
            /* Set: cd to a specific directory. "cwd" + "program" */
            "cwd":  "${workspaceFolder}/src",
                        // "/path/to/custom/directory"
            /* Set arguments. Splitting it by blank character */
            // e.g. python main.py --config ../configs/sls_fusion_sceneflow.config
            "args": ["--config", "../configs/sls_fusion_sceneflow.config"]
        }
    ]
}

In the launch.json file above, we define the python env by setting the pythonPath variable, but how to use the python env in a docker container for run/ debug? See this post Docker inside VS Code.

C++ in VS Code

We have a C++ project as below and we want to build, run and debug the main output in VS Code.

1
2
3
4
5
6
7
8
9
10
11
12
13
$ tree
├── CMakeLists.txt
├── Doxyfile
├── include
│   ├── basic_app.hpp
│   ├── basic.hpp
│   └── google_learn
│       └── easy.hpp
└── src
    ├── basic_app.cpp
    ├── basic.cpp
    ├── easy.cpp
    └── main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(hello c++)

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS_DEBUG "-g")
# set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")

# set(SOURCES "src/main.cpp" "src/basic.cpp" "src/basic_app.cpp" "src/google_learn/easy.cpp")
file(GLOB_RECURSE SOURCES "src/*.cpp")

add_executable(output ${SOURCES})

target_include_directories(output
    PRIVATE
        ${PROJECT_SOURCE_DIR}/include
)

Building (Compiling and Linking):

  • Using command line g++
    1
    2
    
      mkdir build && cd build
      g++ -Wall -g -I../include ../src/*.cpp -o output
    
  • Or, using command line cmake
    1
    2
    
      mkdir build && cd build
      cmake .. && make
    
  • Or, in VS Code, using CMake (Activity Bar) (ms-vscode.cmake-tools extension): Config > Build.
  • Or, in VS Code, creating tasks.json for config build tasks with cmake or g++ and then Run Build Task (Ctrl+Shift+B)

Run/ debug by creating a launch.json with "type": "cppdbg".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ project", // Set project's name
            "type": "cppdbg", // C++ debugging configuration
            "request": "launch",
            "program": "${workspaceFolder}/build/output",
            // "args": [""],
            // "stopAtEntry": false,
            "cwd": "${workspaceFolder}/build",
            // "environment": [],
            // "externalConsole": false,
            "MIMode": "gdb", // debugger interface mode
            "miDebuggerPath": "/usr/bin/gdb" // path to the debugger executable
        }
    ]
}

Conclusion

VS Code has proven to be a robust and dynamic IDE that empowers developers to excel in their coding pursuits. Its wide array of extensions, customization options, and debugging tools have made it an indispensable tool in the developer’s toolkit.

References

  1. VS Code docs: code.visualstudio.com/docs
  2. Debugging in VS Code: code.visualstudio.com/docs/editor/debugging
  3. Python debugging in VS Code: code.visualstudio.com/docs/python/debugging
  4. Using C++ on Linux in VS Code: code.visualstudio.com/docs/cpp/config-linux
  5. Get started with CMake Tools on Linux: code.visualstudio.com/docs/cpp/cmake-linux
  6. Configure C/C++ debugging: code.visualstudio.com/docs/cpp/launch-json-reference

Appendix

Errors

  • VS Code Debugger not working for python: Python Extension version v2022.10.1 running on Ubuntu 18.04 with python 3.6.9. → python3.6 → 3.9
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
      # Install python3.9
      sudo apt install build-essential zlib1g-dev \
          libncurses5-dev libgdbm-dev libnss3-dev \
          libssl-dev libreadline-dev libffi-dev curl \
          software-properties-common
      wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tar.xz
      tar -xf Python-3.9.0.tar.xz
      cd Python-3.9.0
      ./configure
      sudo make altinstall
      python3.9 --version
      which python3.9
    

    Then, in VS Code, change to python3.9 version (status bar)