乐闻世界logo
搜索文章和话题

How do I set up Visual Studio Code to compile C++ code?

1个答案

1

Visual Studio Code is a lightweight yet powerful source code editor that supports multiple programming languages, including C++. To compile C++ code in Visual Studio Code, follow these steps:

1. Install Visual Studio Code

First, ensure Visual Studio Code is installed. Download and install it from the Visual Studio Code official website.

2. Install the C++ Compiler

For Windows users, it is recommended to install the MinGW compiler. Download MinGW from the MinGW official website and install the GCC compiler.

For macOS users, you can obtain the GCC compiler by installing Xcode Command Line Tools. Simply run xcode-select --install in the terminal.

Linux users can install GCC via their package manager. For example, on Ubuntu, use the command sudo apt install g++.

3. Install the C++ Extension

In Visual Studio Code, open the Extensions marketplace, search for 'C++', or directly install the 'C/C++' extension published by Microsoft.

4. Configure Task to Run the Compilation Process

Open the terminal by clicking 'Terminal' in the View menu or pressing Ctrl+ key. Then press Ctrl+Shift+P to open the command palette, type 'Configure Tasks', select 'Tasks: Configure Task', and choose 'C/C++: g++.exe build active file' (for Windows users) to automatically create a task configuration file.

5. Write Your C++ Code

Create a new file, save it with a .cpp extension, such as hello.cpp, and write your C++ code.

6. Build and Run Your Code

Use Ctrl+Shift+B to build your code, which will invoke the previously configured compilation task. After successful compilation, you can run the generated executable file in the Visual Studio Code terminal.

Example

Suppose your C++ program looks like this:

cpp
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }

Save and press Ctrl+Shift+B to compile. Then run the generated executable file in the terminal (e.g., ./a.exe on Windows, or ./a.out on Linux and macOS), and you will see the output 'Hello, World!'

2024年8月10日 08:33 回复

你的答案