Как запустить hello world в visual studio code
This tutorial shows you how to write and run Hello World program in Java with Visual Studio Code. It also covers a few advanced features, which you can explore by reading other documents in this section.
For an overview of the features available for Java in VS Code, see Java Language Overview.
If you run into any issues when following this tutorial, you can contact us by entering an issue.
Setting up VS Code for Java development
Coding Pack for Java
To help you set up quickly, you can install the Coding Pack for Java, which includes VS Code, the Java Development Kit (JDK), and essential Java extensions. The Coding Pack can be used as a clean installation, or to update or repair an existing development environment.
Note: The Coding Pack for Java is only available for Windows and macOS. For other operating systems, you will need to manually install a JDK, VS Code, and Java extensions.
Installing extensions
If you are an existing VS Code user, you can also add Java support by installing the Extension Pack for Java, which includes these extensions:
The Extension Pack for Java provides a Quick Start guide and tips for code editing and debugging. It also has a FAQ that answers some frequently asked questions. Use the command Java: Tips for Beginners from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) to launch the guide.
You can also install extensions separately. The Extensions Guide is provided to help you. You can launch the guide with the Java: Extensions Guide command.
Installing and setting up a Java Development Kit (JDK)
To use Java within Visual Studio Code, you need to install a Java Development Kit (JDK) on your local environment. JDK is a software development environment used for developing Java applications.
Supported Java versions
The Extension Pack for Java supports Java version 1.5 or above.
Note: To configure JDKs for your projects, see Configure Runtime for Projects. To enable Java preview features, see How can I use VS Code with new Java versions.
Installing a Java Development Kit (JDK)
If you have never installed a JDK before and need to install one, we recommend you to choose from one of these sources:
Creating a source code file
Create a folder for your Java program and open the folder with VS Code. Then in VS Code, create a new file and save it with the name Hello.java . When you open that file, the Java Language Server automatically starts loading, and you should see a language status item with a loading icon on the right side of the Status Bar showing the language status is busy. After it finishes loading, you can hover on the language status item and find the loading process has been finished successfully. You can also choose to pin the status item in the status bar.
Note: If you open a Java file in VS Code without opening its folder, the Java Language Server might not work properly.
VS Code will also try to figure out the correct package for the new type and fill the new file from a template. See Create new file.
You can also create a Java project using the Java: Create Java Project command. Bring up the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and then type java to search for this command. After selecting the command, you will be prompted for the location and name of the project. You can also choose your build tool from this command.
Visual Studio Code also supports more complex Java projects — see Project Management.
Editing source code
You can use code snippets to scaffold your classes and methods. VS Code also provides IntelliSense for code completion, and various refactor methods.
To learn more about editing Java, see Java Editing.
Running and debugging your program
To run and debug Java code, set a breakpoint, then either press F5 on your keyboard or use the Run > Start Debugging menu item. You can also use the Run|Debug CodeLens option in the editor. After the code compiles, you can see all your variables and threads in the Run view.
The debugger also supports advanced features such as Hot Code Replace and conditional breakpoints.
For more information, see Java Debugging.
More features
The editor also has many more capabilities to assist with your Java workload.
Предварительные требования
Создание приложения
Запустите Visual Studio Code.
В главном меню выберите Файл>Открыть папку (в macOS выберите File>Open. (Файл > Открыть)).
В диалоговом окне Открыть папку создайте папку HelloWorld и выберите ее. Затем щелкните Выбрать папку (или Открыть в macOS).
Имя папки по умолчанию преобразуется в имя проекта и имя пространства имен. Вы добавите код позже в этом учебнике. Предполагается, что пространство имен проекта — HelloWorld .
В диалоговом окне о доверии авторам файлов в этой папке выберите Да, я доверяю авторам.
Откройте терминал в Visual Studio Code, выбрав в основном меню пункт Вид>Терминал.
Откроется окно Терминал с командной строкой в папке HelloWorld.
В окне терминала введите следующую команду:
Шаблон проекта создает простое приложение, которое отображает "Hello World" в окне консоли, вызывая метод Console.WriteLine(String) из файла Program.cs.
Замените содержимое Program.cs кодом из этого примера.
При первом редактировании файла .cs в Visual Studio Code будет предложено добавить недостающие ресурсы для сборки и отладки приложения. Выберите Да и Visual Studio Code создаст папку .vscode с файлами launch.json и tasks.json.
Если запрос не отображается или вы случайно закрываете его без нажатия кнопки "Да", выполните следующие действия, чтобы создать launch.json и tasks.json:
- Выберите "КонфигурацияRunAdd>" в меню.
- Выберите .NET 5+ и .NET Core в командной строке "Выбор среды ".
Код определяет класс Program с одним методом Main , который принимает массив String в качестве аргумента. Main — точка входа в приложение. Это метод, который автоматически вызывается средой выполнения при запуске приложения. Все аргументы, предоставленные в командной строке при запуске приложения, доступны через массив args.
Запуск приложения
Выполните следующие команды в окне терминала:
Программа отображает "Hello World!" и заканчивается.
Улучшение приложения
Давайте расширим приложение. Теперь у пользователя будет запрашиваться имя, которое затем будет отображаться с датой и временем.
Откройте файл Program.cs.
В Program.cs замените содержимое метода Main (строка, вызывающая Console.WriteLine ) следующим кодом:
Этот код отображает запрос в окне консоли и ожидает, чтобы пользователь ввел строку текста и нажал клавишу ВВОД . Приложение сохраняет полученную строку в переменной с именем name . Оно также получает значение свойства DateTime.Now, которое содержит текущее локальное время, и присваивает его переменной с именем currentDate . Затем оно отображает эти значения в окне консоли. Наконец, приложение выводит запрос в окне консоли и вызывает метод Console.ReadKey(Boolean) для ожидания ввода данных пользователем.
Знак доллара ( $ ) перед строкой позволяет вставить такие выражения, как имена переменных, в фигурные скобки в строке. Значение выражения вставляется в строку вместо выражения. Такой синтаксис называется интерполированными строками.
В Visual Studio Code необходимо явно сохранить изменения. В отличие от Visual Studio, изменения файлов не сохраняются автоматически при сборке и запуске приложения.
Запустите программу еще раз:
В ответ на приглашение в командной строке введите имя и нажмите клавишу ВВОД .
Нажмите любую клавишу для выхода из программы.
Дополнительные ресурсы
Следующие шаги
Предварительные требования
Создание приложения
Запустите Visual Studio Code.
В главном меню выберите Файл>Открыть папку (в macOS выберите File>Open. (Файл > Открыть)).
В диалоговом окне Открытие папки создайте папку HelloWorld и щелкните Выбрать папку (в macOS щелкните Open (Открыть)).
Имя папки по умолчанию преобразуется в имя проекта и имя пространства имен. Вы добавите код позже в этом учебнике. Предполагается, что пространство имен проекта — HelloWorld .
Откройте терминал в Visual Studio Code, выбрав в основном меню пункт Вид>Терминал.
Откроется окно Терминал с командной строкой в папке HelloWorld.
В окне терминала введите следующую команду:
Этот шаблон создает простое приложение Hello World. Он вызывает метод Console.WriteLine(String) для вывода "Hello World!" в окне консоли.
Код шаблона определяет класс Program с одним методом Main , который принимает в качестве аргумента массив String.
Main — точка входа в приложение. Это метод, который автоматически вызывается средой выполнения при запуске приложения. Все аргументы, предоставленные в командной строке при запуске приложения, доступны через массив args.
Запуск приложения
Выполните следующие команды в окне терминала:
Программа отображает "Hello World!" и заканчивается.
Улучшение приложения
Давайте расширим приложение. Теперь у пользователя будет запрашиваться имя, которое затем будет отображаться с датой и временем.
Откройте файл Program.cs, щелкнув его.
Когда в Visual Studio Code будет предложено добавить недостающие ресурсы для сборки и отладки приложения, выберите Да.
В Program.cs замените содержимое метода Main (строка, вызывающая Console.WriteLine ) следующим кодом:
Этот код отображает запрос в окне консоли и ожидает, чтобы пользователь ввел строку текста и нажал клавишу ВВОД . Приложение сохраняет полученную строку в переменной с именем name . Оно также получает значение свойства DateTime.Now, которое содержит текущее локальное время, и присваивает его переменной с именем currentDate . Затем оно отображает эти значения в окне консоли. Наконец, приложение выводит запрос в окне консоли и вызывает метод Console.ReadKey(Boolean) для ожидания ввода данных пользователем.
Знак доллара ( $ ) перед строкой позволяет вставить такие выражения, как имена переменных, в фигурные скобки в строке. Значение выражения вставляется в строку вместо выражения. Такой синтаксис называется интерполированными строками.
В Visual Studio Code необходимо явно сохранить изменения. В отличие от Visual Studio, изменения файлов не сохраняются автоматически при сборке и запуске приложения.
Запустите программу еще раз:
В ответ на приглашение в командной строке введите имя и нажмите клавишу ВВОД .
Нажмите любую клавишу для выхода из программы.
Дополнительные ресурсы
Следующие шаги
Prerequisites
Create the app
Create a .NET console app project named "HelloWorld".
Start Visual Studio Code.
Select File > Open Folder (File > Open. on macOS) from the main menu.
In the Open Folder dialog, create a HelloWorld folder and select it. Then click Select Folder (Open on macOS).
The folder name becomes the project name and the namespace name by default. You'll add code later in the tutorial that assumes the project namespace is HelloWorld .
In the Do you trust the authors of the files in this folder? dialog, select Yes, I trust the authors.
Open the Terminal in Visual Studio Code by selecting View > Terminal from the main menu.
The Terminal opens with the command prompt in the HelloWorld folder.
In the Terminal, enter the following command:
The project template creates a simple application that displays "Hello World" in the console window by calling the Console.WriteLine(String) method in Program.cs.
Replace the contents of Program.cs with the following code:
The first time you edit a .cs file, Visual Studio Code prompts you to add the missing assets to build and debug your app. Select Yes, and Visual Studio Code creates a .vscode folder with launch.json and tasks.json files.
If you don't get the prompt, or if you accidentally dismiss it without selecting Yes, do the following steps to create launch.json and tasks.json:
The code defines a class, Program , with a single method, Main , that takes a String array as an argument. Main is the application entry point, the method that's called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array.
Run the app
Run the following command in the Terminal:
The program displays "Hello World!" and ends.
Enhance the app
Enhance the application to prompt the user for their name and display it along with the date and time.
Replace the contents of the Main method in Program.cs, which is the line that calls Console.WriteLine , with the following code:
This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name . It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate . And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.
The dollar sign ( $ ) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.
Save your changes.
In Visual Studio Code, you have to explicitly save changes. Unlike Visual Studio, file changes are not automatically saved when you build and run an app.
Run the program again:
Respond to the prompt by entering a name and pressing the Enter key.
Press any key to exit the program.
Additional resources
Next steps
Prerequisites
Create the app
Create a .NET console app project named "HelloWorld".
Start Visual Studio Code.
Select File > Open Folder (File > Open. on macOS) from the main menu.
In the Open Folder dialog, create a HelloWorld folder and click Select Folder (Open on macOS).
The folder name becomes the project name and the namespace name by default. You'll add code later in the tutorial that assumes the project namespace is HelloWorld .
Open the Terminal in Visual Studio Code by selecting View > Terminal from the main menu.
The Terminal opens with the command prompt in the HelloWorld folder.
In the Terminal, enter the following command:
The template creates a simple "Hello World" application. It calls the Console.WriteLine(String) method to display " Hello World! " in the console window.
The template code defines a class, Program , with a single method, Main , that takes a String array as an argument:
Main is the application entry point, the method that's called automatically by the runtime when it launches the application. Any command-line arguments supplied when the application is launched are available in the args array.
Run the app
Run the following command in the Terminal:
The program displays "Hello World!" and ends.
Enhance the app
Enhance the application to prompt the user for their name and display it along with the date and time.
Open Program.cs by clicking on it.
Select Yes when Visual Studio Code prompts you to add the missing assets to build and debug your app.
Replace the contents of the Main method in Program.cs, which is the line that calls Console.WriteLine , with the following code:
This code displays a prompt in the console window and waits until the user enters a string followed by the Enter key. It stores this string in a variable named name . It also retrieves the value of the DateTime.Now property, which contains the current local time, and assigns it to a variable named currentDate . And it displays these values in the console window. Finally, it displays a prompt in the console window and calls the Console.ReadKey(Boolean) method to wait for user input.
The dollar sign ( $ ) in front of a string lets you put expressions such as variable names in curly braces in the string. The expression value is inserted into the string in place of the expression. This syntax is referred to as interpolated strings.
Save your changes.
In Visual Studio Code, you have to explicitly save changes. Unlike Visual Studio, file changes are not automatically saved when you build and run an app.
Run the program again:
Respond to the prompt by entering a name and pressing the Enter key.
Press any key to exit the program.
Additional resources
Next steps
In this tutorial, you use Python 3 to create the simplest Python "Hello World" application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).
This tutorial introduces you to VS Code as a Python environment, primarily how to edit, run, and debug code through the following tasks:
- Write, run, and debug a Python "Hello World" Application
- Learn how to install packages by creating Python virtual environments
- Write a simple Python script to plot figures within VS Code
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:
- VS Code
- VS Code Python extension
- Python 3
Install Visual Studio Code and the Python Extension
If you have not already done so, install VS Code.
Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it's published by Microsoft.
Install a Python interpreter
Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.
Windows
Note: If you don't have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of Python 3.7, Python 3.8, Python 3.9, and Python 3.10. Be aware that you might have compatibility issues with some packages using this method.
macOS
The system install of Python on macOS is not supported. Instead, an installation through Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.
Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.
Linux
The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.
Other options
Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.
Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you'll also want to install the Remote - WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.
Verify the Python installation
To verify that you've installed Python successfully on your machine, run one of the following commands (depending on your operating system):
Linux/macOS: open a Terminal Window and type the following command:
Windows: open a command prompt and run the following command:
If the installation was successful, the output window should show the version of Python that you installed.
Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).
Start VS Code in a project (workspace) folder
Using a command prompt or terminal, create an empty folder called "hello", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:
Note: If you're using an Anaconda distribution, be sure to use an Anaconda command prompt.
By starting VS Code in a folder, that folder becomes your "workspace". VS Code stores settings that are specific to that workspace in .vscode/settings.json , which are separate from user settings that are stored globally.
Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.
Select a Python interpreter
Python is an interpreted language, and in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.
From within VS Code, select a Python 3 interpreter by opening the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, see Configuring Python environments.
Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda) , for example Python 3.7.3 64-bit ('base':conda) .
Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.
Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.
Create a Python Hello World source code file
From the File Explorer toolbar, select the New File button on the hello folder:
Name the file hello.py , and it automatically opens in the editor:
By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.
Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.
Now that you have a code file in your Workspace, enter the following source code in hello.py :
When you start typing print , notice how IntelliSense presents auto-completion options.
IntelliSense and auto-completions work for standard Python modules as well as other packages you've installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg. :
Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file ( ⌘S (Windows, Linux Ctrl+S ) ).
For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.
Run Hello World
It's simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.
The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):
There are three other ways you can run Python code within VS Code:
Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):
Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.
From the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.
Configure and run the debugger
Let's now try debugging our simple Hello World program.
First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9 . Alternately, just click in the editor's left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.
Next, to initialize the debugger, press F5 . Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.
Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.
These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.
You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.
The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.
A debug toolbar appears along the top with the following commands from left to right: continue ( F5 ), step over ( F10 ), step into ( F11 ), step out ( ⇧F11 (Windows, Linux Shift+F11 ) ), restart ( ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 ) ), and stop ( ⇧F5 (Windows, Linux Shift+F5 ) ).
The Status Bar also changes color (orange in many themes) to indicate that you're in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.
To continue running the program, select the continue command on the debug toolbar ( F5 ). The debugger runs the program to the end.
Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg , hovering over the variable will display the string Hello world in a box above the variable.
You can also work with variables in the Debug Console (If you don't see it, select Debug Console in the lower right area of VS Code, or select it from the . menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:
Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. "Hello World" appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.
If you restart the debugger, the debugger again stops on the first breakpoint.
To stop running a program before it's complete, use the red square stop button on the debug toolbar ( ⇧F5 (Windows, Linux Shift+F5 ) ), or use the Run > Stop debugging menu command.
For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.
Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn't stop the program. For more information, see Logpoints in the main VS Code debugging article.
Install and use packages
Let's now run an example that's a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)
Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py , and paste in the following source code:
Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter .
Next, try running the file in the debugger using the "Python: Current file" configuration as described in the last section.
Unless you're using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, "ModuleNotFoundError: No module named 'matplotlib'". Such a message indicates that the required package isn't available in your system.
To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) ). This command opens a command prompt for your selected interpreter.
A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:
Note: For additional information about virtual environments, see Environments.
Create and activate the virtual environment
Note: When you create a new virtual environment, you should be prompted by VS Code to set it as the default for your workspace folder. If selected, the environment will automatically be activated when you open a new terminal.
For Windows
If the activate command generates the message "Activate.ps1 is not digitally signed. You cannot run this script on the current system.", then you need to temporarily change the PowerShell execution policy to allow scripts to run (see About Execution Policies in the PowerShell documentation):
For macOS/Linux
Select your new environment by using the Python: Select Interpreter command from the Command Palette.
Install the packages
Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:
Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.
For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.
Next steps
You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.
To learn to build web apps with the Django and Flask frameworks, see the following tutorials:
In this tutorial, you configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger from mingw-w64 to create programs that run on Windows.
After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you about GCC, GDB, Mingw-w64, or the C++ language. For those subjects, there are many good resources available on the Web.
If you have any problems, 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 steps:
Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for 'c++' in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
Get the latest version of Mingw-w64 via MSYS2, which provides up-to-date native builds of GCC, Mingw-w64, and other helpful C++ tools and libraries. You can download the latest installer from the MSYS2 page or use this link to the installer.
Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command, especially Step 7, when you will install the actual Mingw-w64 toolset ( pacman -S --needed base-devel mingw-w64-x86_64-toolchain ).
Add the path to your Mingw-w64 bin folder to the Windows PATH environment variable by using the following steps:
- In the Windows search bar, type 'settings' to open your Windows Settings.
- Search for Edit environment variables for your account.
- Choose the Path variable in your User variables and then select Edit.
- Select New and add the Mingw-w64 destination folder path to the system path. The exact path depends on which version of Mingw-w64 you have installed and where you installed it. If you used the settings above to install Mingw-w64, then add this to the path: C:\msys64\mingw64\bin .
- Select OK to save the updated PATH. You will need to reopen any console windows for the new PATH location to be available.
Check your MinGW installation
To check that your Mingw-w64 tools are correctly installed and available, open a new Command Prompt and type:
If you don't see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
Create Hello World
From a Windows command prompt, create an empty folder called projects where you can place all your VS Code projects. Then create a sub-folder called helloworld , navigate into it, and open VS Code in that folder by entering the following commands:
The "code ." command opens VS Code in the current working folder, which becomes your "workspace". Accept the Workspace Trust dialog by selecting Yes, I trust the authors since this is a folder you created.
As you go through the tutorial, you will see three files created in a .vscode folder in the workspace:
- tasks.json (build instructions)
- launch.json (debugger settings)
- c_cpp_properties.json (compiler path and IntelliSense settings)
Add a source code file
In the File Explorer title bar, select the New File button and name the file helloworld.cpp .
Add hello world source code
Now paste in this source code:
Now press ⌘S (Windows, Linux Ctrl+S ) to save the file. Notice how the file you just added appears in the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ) in the side bar of VS Code:
You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.
The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You'll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.
Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).
Explore IntelliSense
In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:
You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.
Build helloworld.cpp
Next, you'll create a tasks.json file to tell VS Code how to build (compile) the program. This task will invoke the g++ compiler to create an executable file based on the source code.
From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a tasks.json file in a .vscode folder and open it in the editor.
Your new tasks.json file should look similar to the JSON below:
The command setting specifies the program to run; in this case that is g++. The args array specifies the command-line arguments that will be passed to g++. These arguments must be specified in the order expected by the compiler. This task tells g++ to take the active file ( $ ), compile it, and create an executable file in the current directory ( $ ) with the same name as the active file but with the .exe extension ( $.exe ), resulting in helloworld.exe for our example.
Note: You can learn more about tasks.json variables in the variables reference.
The label value is what you will see in the tasks list; you can name this whatever you like.
The "isDefault": true value in the group object specifies that this task will be run when you press ⇧⌘B (Windows, Linux Ctrl+Shift+B ) . This property is for convenience only; if you set it to false, you can still run it from the Terminal menu with Tasks: Run Build Task.
Running the build
Go back to helloworld.cpp . Your task builds the active file and you want to build helloworld.cpp .
To run the build task defined in tasks.json , press ⇧⌘B (Windows, Linux Ctrl+Shift+B ) or from the Terminal main menu choose Run Build Task.
When the task starts, you should see the Integrated Terminal panel appear below the source code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful g++ build, the output looks something like this:
Create a new terminal using the + button and you'll have a new terminal with the helloworld folder as the working directory. Run dir and you should now see the executable helloworld.exe .
You can run helloworld in the terminal by typing helloworld.exe (or .\helloworld.exe if you use a PowerShell terminal).
Note: You might need to press Enter a couple of times initially to see the PowerShell prompt in the terminal. This issue should be fixed in a future release of Windows.
Modifying tasks.json
You can modify your tasks.json to build multiple C++ files by using an argument like "$\\*.cpp" instead of $ . This will build all .cpp files in your current folder. You can also modify the output filename by replacing "$\\$.exe" with a hard-coded filename (for example "$\\myProgram.exe" ).
Debug helloworld.cpp
Next, you'll create a launch.json file to configure VS Code to launch the GDB debugger when you press F5 to debug the program.
- From the main menu, choose Run >Add Configuration. . VS Code creates an empty launch.json file.
- Copy and paste the following configuration into launch.json :
The program setting specifies the program you want to debug. Here it is set to the active file folder $ and active filename with the .exe extension $.exe , which if helloworld.cpp is the active file will be helloworld.exe .
By default, the C++ extension won't add any breakpoints to your source code and the stopAtEntry value is set to false .
Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.
Note: The preLaunchTask setting is used to specify task to be executed before launch. Make sure it is consistent with the tasks.json file label setting.
Start a debugging session
- Go back to helloworld.cpp so that it is the active file.
- Press F5 or from the main menu choose Run > Start Debugging. Before you start stepping through the source code, let's take a moment to notice several changes in the user interface:
The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.
The editor highlights the first statement in the main method. This is a breakpoint that the C++ extension automatically sets for you:
The Run view on the left shows debugging information. You'll see an example later in the tutorial.
At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.
Step through the code
Now you're ready to start stepping through the code.
Click or press the Step over icon in the debugging control panel.
This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.
In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.
Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.
Press Step over again to execute the cout statement. (Note that as of the March 2019 release, the C++ extension does not print any output to the Debug Console until the loop exits.)
If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!
To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp tab in the code editor, putting the insertion point somewhere on the cout statement inside the loop, and pressing F9 . A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.
Then press F5 to start execution from the current line in the standard library header. Execution will break on cout . If you like, you can press F9 again to toggle off the breakpoint.
When the loop has completed, you can see the output in the Integrated Terminal, along with some other diagnostic information that is output by GDB.
Set a watch
Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.
Place the insertion point inside the loop. In the Watch window, click the plus sign and in the text box, type word , which is the name of the loop variable. Now view the Watch window as you step through the loop.
Add another watch by adding this statement before the loop: int i = 0; . Then, inside the loop, add this statement: ++i; . Now add a watch for i as you did in the previous step.
To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.
C/C++ configurations
If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.
You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called c_cpp_properties.json in the .vscode folder.
Here, we've changed the Configuration name to GCC, set the Compiler path dropdown to the g++ compiler, and the IntelliSense mode to match the compiler (gcc-x64)
Visual Studio Code places these settings in .vscode\c_cpp_properties.json . If you open that file directly, it should look something like this:
You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.
Compiler path
The extension uses the compilerPath setting to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide features like smart completions and Go to Definition navigation.
The C/C++ extension attempts to populate compilerPath with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.
The compilerPath search order is:
- First check for the Microsoft Visual C++ compiler
- Then look for g++ on Windows Subsystem for Linux (WSL)
- Then g++ for Mingw-w64.
If you have Visual Studio or WSL installed, you may need to change compilerPath to match the preferred compiler for your project. For example, if you installed Mingw-w64 version 8.1.0 using the i686 architecture, Win32 threading, and sjlj exception handling install options, the path would look like this: C:\Program Files (x86)\mingw-w64\i686-8.1.0-win32-sjlj-rt_v6-rev0\mingw64\bin\g++.exe .
Troubleshooting
MSYS2 is installed, but g++ and gdb are still not found
You must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools.
MinGW 32-bit
If you need a 32-bit version of the MinGW toolset, consult the Downloading section on the MSYS2 wiki. It includes links to both 32-bit and 64-bit installation options.
Читайте также: