C++ Setup

Starter

Jacob Xie published on
3 min, 408 words

Categories: Doc

Tags: C++

C++ and WSL

These documentation is completely followed by the official VsCode document.

Using VsCode to edit source code, compiling the source code on Linux using the g++ compiler and debugging on Linux using GDB. They are not installed by default on Ubuntu.

Environment

  1. update sys dependencies:

    sudo apt-get update
    

    or download the latest versions of the system packages as well by:

    sudo apt-get update && sudo apt-get dist-upgrade
    
  2. install GNU compiler tools and the GDB debugger:

    sudo apt-get install build-essential gdb
    
  3. verify g++ and gdb:

    whereis g++
    whereis gdb
    

After setting up the environment, create a .cpp file and vscode will pop up a hint window to ask you to install C/C++ extensions. Let's omit this step and head forward to the next step.

Alternative

  1. Install the desired version:

    sudo apt install gcc-10
    sudo apt install g++-10
    
  2. Switch to the version:

    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 10
    sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 10
    
  3. Test with:

    gcc --version
    g++ --version
    

Build

Choose Terminal > Configure Default Build Task and in the dropdown select C/C++: g++ build active file. A tasks.json file should be created in the .vscode folder. Learn more tasks.json variables in the variables reference.

Run

Choose Tasks: Run Build Task and will see an executable file after the build is done.

Debug

Press F5 and choose C++ (GDB/LLDB), then choose g++ build and debug active file from the dropdown. This will create a launch.json file in the .vscode folder. More details please visit debug-helloworldcpp.

Configurations

In order to get more control over the C/C++ extension, we can create a c_cpp_properties.json file in .vscode folder via C/C++: Edit Configuration (UI) command.

CMake

  1. dependencies:

    sudo apt-get install build-essential libssl-dev
    
  2. check the latest released version and download:

    wget https://github.com/Kitware/CMake/releases/download/v3.23.4/cmake-3.23.4.tar.gz
    
  3. extract:

    tar -zxvf cmake-*
    
  4. install:

    cd cmake-3.23.4
    ./bootstrap
    
  5. make and install:

    make
    sudo make install
    
  6. check installed version:

    cmake --version
    

Create a CMake project

reference