como-crear-un-proyecto-de-cpp-con-visual-studio-code

Create a C++ Project with Visual Studio Code

  • 5 min

Let’s see how to create a new project in C++ with Visual Studio Code, how to run it, and debug it.

Once we have VS Code installed, the compiler, and the extensions installed, create a new folder for the project (to better organize your project) and open this folder in VSCode with File > Open Folder.

Now create a new C++ file by clicking File > New File (or pressing Ctrl+N), named main.cpp (for example).

In this file, paste this code.

#include <iostream>

int main() {
    std::cout << "Hello, world in C++ from LuisLlamas.es!" << std::endl;
    return 0;
}
Copied!

We will see each line in detail later. For now, don’t worry, we are just setting up the environment.

You already have a very simple program. Now let’s run it 👇.

Run the code

From VSCode

To launch our code from Visual Studio Code, press F5. The first time, a dropdown will appear to choose the debugger.

vscode-gdb

Select C++ (GDB/LLLDB) and another dropdown will appear to choose the configuration.

vscode-gcc

Here we choose C/C++ g++ build and debug active file and (finally) the program will run.

In the Terminal tab, you will see the program’s output (which includes a command with several lines). And at the end, the output message.

Hello, world in C++ from LuisLlamas.es!
Copied!

Congratulations, you now have VSCode configured to work with C++ 🎉.

The next times you want to run the program, simply press F5, and it will launch without having to choose anything from dropdowns.

From the terminal

Alternatively, if you want to do the compilation manually, you could do it like this. First, compile the code using GCC with the following command:

g++ hola_mundo.cpp -o hola_mundo

Now it will create an executable file, which we can run (obviously, because it’s executable 😆).

hola_mundo.exe

./hola_mundo

Configuration of compilation and execution tasks

The VSCode configuration for compilation and debugging is based on two files tasks.json and launch.json, which are saved in the project folder (in the .vscode subfolder).

  • tasks.json: Configures automatic tasks (for example, compiling code).
  • launch.json: Configures the debugger and program execution within VSCode.

vscode-task-launch-json