Cách chạy C++ trên Visual Studio Code

In this tutorial, you will configure Visual Studio Code to use the GCC C++ compiler [g++] and GDB debugger on Linux. GCC stands for GNU Compiler Collection; GDB is the GNU debugger.

After configuring VS Code, you will compile and debug a simple C++ program in VS Code. This tutorial does not teach you GCC, GDB, Ubuntu or the C++ language. For those subjects, there are many good resources available on the Web.

If you have trouble, feel free to file an issue for this tutorial in the VS Code documentation repository.

Prerequisites

To successfully complete this tutorial, you must do the following:

Ensure GCC is installed

Although you'll use VS Code to edit your source code, you'll compile the source code on Linux using the g++ compiler. You'll also use GDB to debug. These tools are not installed by default on Ubuntu, so you have to install them. Fortunately, that's easy.

First, check to see whether GCC is already installed. To verify whether it is, open a Terminal window and enter the following command:

gcc -v

If GCC isn't installed, run the following command from the terminal window to update the Ubuntu package lists. An out-of-date Linux distribution can sometimes interfere with attempts to install new packages.

sudo apt-get update

Next install the GNU compiler tools and the GDB debugger with this command:

sudo apt-get install build-essential gdb

Create Hello World

From the terminal window, create an empty folder called projects to store your VS Code projects. Then create a subfolder called helloworld, navigate into it, and open VS Code in that folder by entering the following commands:

mkdir projects cd projects mkdir helloworld cd helloworld code .

The code . command opens VS Code in the current working folder, which becomes your "workspace". As you go through the tutorial, you will create three files in a .vscode folder in the workspace:

  • tasks.json [compiler build settings]
  • launch.json [debugger settings]
  • c_cpp_properties.json [compiler path and IntelliSense settings]

Add hello world source code file

In the File Explorer title bar, select New File and name the file helloworld.cpp.

Paste in the following source code:

#include #include #include using namespace std; int main[] { vector msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"}; for [const string& word : msg] { cout

Chủ Đề