Visual studio 2022 как запустить код
Перейти к содержимому

Visual studio 2022 как запустить код

  • автор:

Visual studio 2022 как запустить код

Чтобы облегчить написание, а также тестирование и отладку программного кода нередко используют специальные среды разработки, в частности, Visual Studio. Рассмотрим создание приложений на C# с помощью бесплатной и полнофункциональной среды Visual Studio Community 2022, которую можно загрузить по следующему адресу: Microsoft Visual Studio 2022

Установка Visual Studio 2022

После загрузки запустим программу установщика. В открывшемся окне нам будет предложено выбрать те компоненты, которые мы хотим установить вместе Visual Studio. Стоит отметить, что Visual Studio — очень функциональная среда разработки и позволяет разрабатывать приложения с помощью множества языков и платформ. В нашем случае нам будет интересовать прежде всего C# и .NET.

Чтобы добавить в Visual Studio поддержку проектов для C# и .NET 7, в программе установки среди рабочих нагрузок можно выбрать только пункт ASP.NET и разработка веб-приложений . Можно выбрать и больше опций или вообще все опции, однако стоит учитывать свободный размер на жестком диске — чем больше опций будет выбрано, соответственно тем больше места на диске будет занято.

Установка Visual Studio 2022

И при инсталляции Visual Studio на ваш компьютер будут установлены все необходимые инструменты для разработки программ, в том числе фреймворк .NET 7.

После завершения установки создадим первую программу. Она будет простенькой. Вначале откроем Visual Studio. На стартовом экране выберем Create a new project (Создать новый проект)

Создание первого проекта в Visual Studio 2022

На следующем окне в качестве типа проекта выберем Console App , то есть мы будем создавать консольное приложение на языке C#

Проект консольного приложения на C# и .NET 7 в Visual Studio 2022

Чтобы проще было найти нужный тип проекта, в поле языков можно выбрать C# , а в поле типа проектов — Console .

Далее на следующем этапе нам будет предложено указать имя проекта и каталог, где будет располагаться проект.

Создание первого приложения на C#

В поле Project Name дадим проекту какое-либо название. В моем случае это HelloApp .

На следующем окне Visual Studio предложит нам выбрать версию .NET, которая будет использоваться для проекта. Выберем последнюю на данный момент верси. — .NET 7.0:

Установка C# 11 и .NET 7 в Visual Studio

Нажмен на кнопку Create (Создать) для создания проекта, и после этого Visual Studio создаст и откроет нам проект:

Первый проект на C#

В большом поле в центре, которое по сути представляет текстовый редактор, находится сгенерированный по умолчанию код C#. Впоследствии мы изменим его на свой.

Справа находится окно Solution Explorer, в котором можно увидеть структуру нашего проекта. В данном случае у нас сгенерированная по умолчанию структура: узел Dependencies — это узел содержит сборки dll, которые добавлены в проект по умолчанию. Эти сборки как раз содержат классы библиотеки .NET, которые будет использовать C#. Однако не всегда все сборки нужны. Ненужные потом можно удалить, в то же время если понадобится добавить какую-нибудь нужную библиотеку, то именно в этот узел она будет добавляться.

Далее идет непосредственно сам файл кода программы Program.cs , который по умолчанию открыт в центральном окне и который имеет всего две строки:

Первая строка предваряется символами // и представляет комментарии — пояснения к коду.

Вторая строка собственно представляет собой код программы: Console.WriteLine(«Hello World!»); . Эта строка выводит на консоль строку «Hello World!».

Несмотря на то, что программа содержит только одну строку кода, это уже некоторая программа, которую мы можем запустить. Запустить проект мы можем с помощью клавиши F5 или с панели инструментов, нажав на зеленую стрелку. И если вы все сделали правильно, то при запуске приложения на консоль будет выведена строка «Hello World!».

Первое приложение на C# и .NET 7

Теперь изменим весь этот код на следующий:

По сравнению с автоматически сгенерированным кодом я внес несколько изменений. Теперь первой строкой выводится приглашение к вводу.

Метод Console.Write() выводит на консоль некоторую строка. В данном случае это строка «Введите свое имя: «.

На второй строке определяется строковая переменная name, в которую пользователь вводит информацию с консоли:

Ключевое слово var указывает на определение переменной. В данном случае переменная называется name . И ей присваивается результат метода Console.ReadLine() , который позволяет считать с консоли введенную строку. То есть мы введем в консоли строку (точнее имя), и эта строка окажется в переменой name .

Затем введенное имя выводится на консоль:

Чтобы ввести значение переменной name внутрь выводимой на консоль строки, применяются фигурные скобки <>. То есть при выводе строки на консоль выражение будет заменяться на значение переменной name — введенное имя.

Однако чтобы можно было вводить таким образом значения переменных внутрь строки, перед строкой указывается знак доллара $.

Теперь протестируем проект, запустив его на выполнение, также нажав на F5 или зеленую стрелочку.

Первая программа на C#

Скомпилированное приложение можно найти в папке проекта в каталоге bin\Debug\net7.0 . Оно будет называться по имени проекта и иметь расширение exe. И затем этот файл можно будет запускать без Visual Studio, а также переносить его на другие компьютеры, где установлен .NET 7.

Debugging

One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.

Debugging diagram

Debugger extensions

VS Code has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, or any other language that gets transpiled to JavaScript.

For debugging other languages and runtimes (including PHP, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace or select Install Additional Debuggers in the top-level Run menu.

Below are several popular extensions which include debugging support:

Tip: The extensions shown above are dynamically queried. Select an extension tile above to read the description and reviews to decide which extension is best for you.

Start debugging

The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.

It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple "Hello World" JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.

Run and Debug view

To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut ⇧⌘D (Windows, Linux Ctrl+Shift+D ) .

Run and Debug icon

The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.

If running and debugging is not yet configured (no launch.json has been created), VS Code shows the Run start view.

Simplified initial Run and Debug view

Run menu

The top-level Run menu has the most common run and debug commands:

Run menu

Launch configurations

To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.

However, for most debugging scenarios, creating a launch configuration file is beneficial because it allows you to configure and save debugging setup details. VS Code keeps debugging configuration information in a launch.json file located in a .vscode folder in your workspace (project root folder) or in your user settings or workspace settings.

To create a launch.json file, click the create a launch.json file link in the Run start view.

launch configuration

VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:

debug environment selector

Here is the launch configuration generated for Node.js debugging:

If you go back to the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ), you’ll see that VS Code has created a .vscode folder and added the launch.json file to your workspace.

launch.json in Explorer

Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.

Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.

Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.

launch.json IntelliSense

Review all automatically generated values and make sure that they make sense for your project and debugging environment.

Launch versus attach configurations

In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.

If you come from a browser Developer Tools background, you might not be used to "launching from your tool," since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’s quite normal to have your editor launch your process for you, and your editor automatically attaches its debugger to the newly launched process.

The best way to explain the difference between launch and attach is to think of a launch configuration as a recipe for how to start your app in debug mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.

VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.

Add a new configuration

To add a new configuration to an existing launch.json , use one of the following techniques:

  • Use IntelliSense if your cursor is located inside the configurations array.
  • Press the Add Configuration button to invoke snippet IntelliSense at the start of the array.
  • Choose Add Configuration option in the Run menu.

VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.

In order to start a debug session, first select the configuration named Launch Program using the Configuration dropdown in the Run and Debug view. Once you have your launch configuration set, start your debug session with F5 .

Alternatively, you can run your configuration through the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) by filtering on Debug: Select and Start Debugging or typing ‘debug ‘ and selecting the configuration you want to debug.

As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):

debug session

In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.

Debug status

Debug actions

Once a debug session starts, the Debug toolbar will appear on the top of the editor.

Debug Actions

Action Explanation
Continue / Pause
F5
Continue: Resume normal program/script execution (up to the next breakpoint).
Pause: Inspect code executing at the current line and debug line-by-line.
Step Over
F10
Execute the next method as a single command without inspecting or following its component steps.
Step Into
F11
Enter the next method to follow its execution line-by-line.
Step Out
⇧F11 (Windows, Linux Shift+F11 )
When inside a method or subroutine, return to the earlier execution context by completing remaining lines of the current method as though it were a single command.
Restart
⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 )
Terminate the current program execution and start debugging again using the current run configuration.
Stop
⇧F5 (Windows, Linux Shift+F5 )
Terminate the current program execution.

Tip: Use the setting debug.toolBarLocation to control the location of the debug toolbar. It can be the default floating , docked to the Run and Debug view, or hidden . A floating debug toolbar can be dragged horizontally and also down to the editor area.

Run mode

In addition to debugging a program, VS Code supports running the program. The Debug: Run (Start Without Debugging) action is triggered with ⌃F5 (Windows, Linux Ctrl+F5 ) and uses the currently selected launch configuration. Many of the launch configuration attributes are supported in ‘Run’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.

Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.

Breakpoints

Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.

  • Breakpoints in the editor margin are normally shown as red filled circles.
  • Disabled breakpoints have a filled gray circle.
  • When a debugging session starts, breakpoints that cannot be registered with the debugger change to a gray hollow circle. The same might happen if the source is edited while a debug session without live-edit support is running.

If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.

The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is "lazy" and "misplaces" breakpoints in source code that has not yet been executed.

Breakpoints

Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :

breakpoints in overview ruler

Logpoints

A Logpoint is a variant of a breakpoint that does not "break" into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.

A Logpoint is represented by a "diamond" shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).

Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.

Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.

Data inspection

Variables can be inspected in the VARIABLES section of the Run and Debug view or by hovering over their source in the editor. Variable values and expression evaluation are relative to the selected stack frame in the CALL STACK section.

Debug Variables

Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.

Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.

Debug Watch

Variable names and values can be filtered by typing while the focus is on the VARIABLES section.

Filtering in the Variables section

Launch.json attributes

There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.

launch json suggestions

The following attributes are mandatory for every launch configuration:

  • type — the type of debugger to use for this launch configuration. Every installed debug extension introduces a type: node for the built-in Node debugger, for example, or php and go for the PHP and Go extensions.
  • request — the request type of this launch configuration. Currently, launch and attach are supported.
  • name — the reader-friendly name to appear in the Debug launch configuration dropdown.

Here are some optional attributes available to all launch configurations:

  • presentation — using the order , group , and hidden attributes in the presentation object, you can sort, group, and hide configurations and compounds in the Debug configuration dropdown and in the Debug quick pick.
  • preLaunchTask — to launch a task before the start of a debug session, set this attribute to the label of a task specified in tasks.json (in the workspace’s .vscode folder). Or, this can be set to $ to use your default build task.
  • postDebugTask — to launch a task at the very end of a debug session, set this attribute to the name of a task specified in tasks.json (in the workspace’s .vscode folder).
  • internalConsoleOptions — this attribute controls the visibility of the Debug Console panel during a debugging session.
  • debugServer — for debug extension authors only: this attribute allows you to connect to a specified port instead of launching the debug adapter.
  • serverReadyAction — if you want to open a URL in a web browser whenever the program under debugging outputs a specific message to the debug console or integrated terminal. For details see section Automatically open a URI when debugging a server program below.

Many debuggers support some of the following attributes:

  • program — executable or file to run when launching the debugger
  • args — arguments passed to the program to debug
  • env — environment variables (the value null can be used to "undefine" a variable)
  • envFile — path to dotenv file with environment variables
  • cwd — current working directory for finding dependencies and other files
  • port — port when attaching to a running process
  • stopOnEntry — break immediately when the program launches
  • console — what kind of console to use, for example, internalConsole , integratedTerminal , or externalTerminal

Variable substitution

VS Code makes commonly used paths and other values available as variables and supports variable substitution inside strings in launch.json . This means that you do not have to use absolute paths in debug configurations. For example, $ gives the root path of a workspace folder, $ the file open in the active editor, and $ the environment variable ‘Name’. You can see a full list of predefined variables in the Variables Reference or by invoking IntelliSense inside the launch.json string attributes.

Platform-specific properties

Launch.json supports defining values (for example, arguments to be passed to the program) that depend on the operating system where the debugger is running. To do so, put a platform-specific literal into the launch.json file and specify the corresponding properties inside that literal.

Below is an example that passes "args" to the program differently on Windows:

Valid operating properties are "windows" for Windows, "linux" for Linux, and "osx" for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.

Please note that the type property cannot be placed inside a platform-specific section, because type indirectly determines the platform in remote debugging scenarios, and that would result in a cyclic dependency.

In the example below, debugging the program always stops on entry except on macOS:

Global launch configuration

VS Code supports adding a "launch" object inside your User settings. This "launch" configuration will then be shared across your workspaces. For example:

Advanced breakpoint topics

Conditional breakpoints

A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.

  • Expression condition: The breakpoint will be hit whenever the expression evaluates to true .
  • Hit count: The ‘hit count’ controls how many times a breakpoint needs to be hit before it will ‘break’ execution. Whether a ‘hit count’ is respected and the exact syntax of the expression vary among debugger extensions.

You can add a condition and/or hit count when creating a source breakpoint (with the Add Conditional Breakpoint action) or when modifying an existing one (with the Edit Condition action). In both cases, an inline text box with a dropdown menu opens where you can enter expressions:

Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.

An example of condition editing in the BREAKPOINTS view:

If a debugger does not support conditional breakpoints, the Add Conditional Breakpoint and Edit Condition actions will be missing.

Inline breakpoints

Inline breakpoints will only be hit when the execution reaches the column associated with the inline breakpoint. This is particularly useful when debugging minified code which contains multiple statements in a single line.

An inline breakpoint can be set using ⇧F9 (Windows, Linux Shift+F9 ) or through the context menu during a debug session. Inline breakpoints are shown inline in the editor.

Inline breakpoints can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.

Function breakpoints

Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function name is known.

A function breakpoint is created by pressing the + button in the BREAKPOINTS section header and entering the function name. Function breakpoints are shown with a red triangle in the BREAKPOINTS section.

Data breakpoints

If a debugger supports data breakpoints, they can be set from the context menu in the VARIABLES view. The Break on Value Change/Read/Access commands will add a data breakpoint that is hit when the value of the underlying variable changes/is read/is accessed. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.

Debug Console REPL

Expressions can be evaluated with the Debug Console REPL (Read-Eval-Print Loop) feature. To open the Debug Console, use the Debug Console action at the top of the Debug pane or use the View: Debug Console command ( ⇧⌘Y (Windows, Linux Ctrl+Shift+Y ) ). Expressions are evaluated after you press Enter and the Debug Console REPL shows suggestions as you type. If you need to enter multiple lines, use Shift+Enter between the lines and then send all lines for evaluation with Enter . Debug Console input uses the mode of the active editor, which means that the Debug Console input supports syntax coloring, indentation, auto closing of quotes, and other language features.

Debug Console

Note: You must be in a running debug session to use the Debug Console REPL.

Redirect input/output to/from the debug target

Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.

Here are two approaches you might want to consider:

Launch the program to debug ("debug target") manually in a terminal or command prompt and redirect input/output as needed. Make sure to pass the appropriate command line options to the debug target so that a debugger can attach to it. Create and run an "attach" debug configuration that attaches to the debug target.

If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, "<" or ">") as arguments.

Here’s an example launch.json configuration:

This approach requires that the "<" syntax is passed through the debugger extension and ends up unmodified in the Integrated Terminal.

Multi-target debugging

For complex scenarios involving more than one process (for example, a client and a server), VS Code supports multi-target debugging.

Using multi-target debugging is simple: after you’ve started a first debug session, you can just launch another session. As soon as a second session is up and running, the VS Code UI switches to multi-target mode:

  • The individual sessions now show up as top-level elements in the CALL STACK view.
    Callstack View
  • The debug toolbar shows the currently active session (and all other sessions are available in a dropdown menu).
    Debug Actions Widget
  • Debug actions (for example, all actions in the debug toolbar) are performed on the active session. The active session can be changed either by using the dropdown menu in the debug toolbar or by selecting a different element in the CALL STACK view.

Compound launch configurations

An alternative way to start multiple debug sessions is by using a compound launch configuration. A compound launch configuration lists the names of two or more launch configurations that should be launched in parallel. Optionally a preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.

Compound launch configurations are displayed in the launch configuration dropdown menu.

Remote debugging

VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.

There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.

Automatically open a URI when debugging a server program

Developing a web program typically requires opening a specific URL in a web browser in order to hit the server code in the debugger. VS Code has a built-in feature "serverReadyAction" to automate this task.

Here is an example of a simple Node.js Express application:

This application first installs a "Hello World" handler for the "/" URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.

The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an "action" to be performed:

Here the pattern property describes the regular expression for matching the program’s output string that announces the port. The pattern for the port number is put into parenthesis so that it is available as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.

The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.

The resulting URI is then opened outside of VS Code ("externally") with the standard application configured for the URI’s scheme.

Trigger Debugging via Edge or Chrome

Alternatively, the action can be set to debugWithEdge or debugWithChrome . In this mode, a webRoot property can be added that is passed to the Chrome or Edge debug session.

To simplify things a bit, most properties are optional and we use the following fallback values:

  • pattern: "listening on.* (https?://\\S+|[0-9]+)" which matches the commonly used messages "listening on port 3000" or "Now listening on: https://localhost:5001".
  • uriFormat: "http://localhost:%s"
  • webRoot: "$"

Triggering an Arbitrary Launch Config

In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.

The named launch configuration must be in the same file or folder as the one with the serverReadyAction .

Here the serverReadyAction feature in action:

Next steps

To learn about VS Code’s Node.js debugging support, take a look at:

    — Describes the Node.js debugger, which is included in VS Code. — The Node.js debugger also supports TypeScript debugging.

To see tutorials on the basics of Node.js debugging, check out these videos:

    — Showcases the basics of debugging. — Shows how to attach a debugger to a running Node.js process.

To learn about debugging support for other programming languages via VS Code extensions:

Как запустить код в Visual Studio Code

Работа в VS Code

Один из самых популярных редакторов исходного кода Visual Studio Code очень удобен для начинающих. Удобный интерфейс и расширенные возможности привлекают как начинающих, так и опытных программистов.

Если вы новичок в VS Code и ищете упрощенное руководство по запуску кода, вы попали по адресу. Мы расскажем вам о настройке необходимого программного обеспечения и выполнении кода с использованием знакомых языков, таких как C/C++ и Python.

Запуск C++ кода

  1. Откройте VS Code.
  2. Выберите значок просмотра расширений на панели активности или используйте комбинацию клавиш (Ctrl+Shift+X).
  3. Введите в строку поиска ‘C++’.
  4. Установите плагин.

После установки расширения, при открытии или создании *.cpp файла у вас будет подсветка синтаксиса, интеллектуальные завершения (IntelliSense), а также проверка ошибок.

Установка компилятора

C++ — компилируемый язык, то есть исходный код программы должен быть переведен (скомпилирован), прежде чем он будет запущен на компьютере. VS Code — это, прежде всего, редактор, и для выполнения большей части рабочего процесса разработки он полагается на инструменты командной строки. Расширение C/C++ не включает компилятор C++ или отладчик. Нужно будет установить эти инструменты или использовать уже установленные на вашем компьютере.

Возможно, компилятор и отладчик C++ уже есть в вашей учебной или рабочей среде разработки. Узнайте у своих преподавателей или коллег, как установить рекомендуемый набор инструментов C++ (компилятор, отладчик, проектную систему, линтер).

На некоторых платформах, таких как Linux или macOS, компилятор C++ уже установлен. В большинстве дистрибутивов Linux установлен GNU Compiler Collection (GCC), а пользователи macOS могут получить инструменты Clang вместе с Xcode.

  1. Установите MinGW
  2. Выберите нужный компилятор, потом перейдите в вкладку installation и нажмите apply change для сохранения настроек. Компилятор начнет скачиваться.

Где main.cpp — имя вашего файлы.

При сохранении файла, копилятор скомпилирует программу и можно будет запустить ее в терминале.

Видеоинструкция для подробного ознакомления

Запуск Python кода

Простой способ запуска Python и он не требует никакой настройки:

Установите расширение Code Runner .

Откройте файл кода Python в текстовом редакторе.

Чтобы запустить код Python:

  1. используйте сочетание клавиш Ctrl + Alt + N;
  2. или нажмите F1, а затем выберите Run Code (Запуск кода);
  3. или щелкните правой кнопкой мыши в текстовом редакторе и выберите Run Code в контекстном меню редактора;
  4. или нажмите кнопку Run Code в меню заголовка редактора.

Чтобы остановить запущенный код:

  1. используйте сочетание клавиш Ctrl + Alt + M
  2. или нажмите F1, а затем выберите Stop Code Run
  3. или щелкните правой кнопкой мыши на выходном канале и выберите Stop Code Run в контекстном меню.

Если вы хотите добавить путь к Python, вы можете перейти в меню Файл → Предпочтения → Настройки и добавить путь к Python, как показано ниже:

«code-runner.executorMap»:
<
«python»: «\»C:\\\Program Files\\\\Python35\\\python.exe\» -u»
>

Если вы уже установили расширение Python и вручную настроили интерпретатор, вы можете настроить ваш файл settings.json следующим образом:

<
«python.pythonPath»: «C:\\\\python36\\\\python36.exe»,
«code-runner.executorMap»:
<
«python»: «$pythonPath -u $fullFileName».
>
>

Как запустить HTML, JS

Html файл вы можете открыть с помощью браузера, VS code может только редактировать содержимое документа.

Name already in use

visualstudio-docs / docs / get-started / csharp / tutorial-debugger.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Tutorial: Learn to debug C# code using Visual Studio

This article introduces the features of the Visual Studio debugger in a step-by-step walkthrough. If you want a higher-level view of the debugger features, see First look at the debugger. When you debug your app, it usually means that you are running your application with the debugger attached. When you do this, the debugger provides many ways to see what your code is doing while it runs. You can step through your code and look at the values stored in variables, you can set watches on variables to see when values change, you can examine the execution path of your code, see whether a branch of code is running, and so on. If this is the first time that you’ve tried to debug code, you might want to read Debugging for absolute beginners before going through this article.

Although the demo app is C#, most of the features are applicable to C++, Visual Basic, F#, Python, JavaScript, and other languages supported by Visual Studio (F# does not support Edit-and-continue. F# and JavaScript do not support the Autos window). The screenshots are in C#.

In this tutorial, you will:

  • Start the debugger and hit breakpoints.
  • Learn commands to step through code in the debugger
  • Inspect variables in data tips and debugger windows
  • Examine the call stack

You must have Visual Studio 2022 installed and the .NET desktop development workload.

You must have Visual Studio 2019 installed and the .NET Core cross-platform development workload.

If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features. , which opens the Visual Studio Installer. The Visual Studio Installer launches. Choose the .NET Core cross-platform development workload, then choose Modify.

If you already have Visual Studio but the .NET desktop development workload isn’t installed, go to Tools > Get Tools and Features. , which launches the Visual Studio Installer. In the Visual Studio Installer, choose the .NET desktop development workload, then choose Modify.

Create a project

First, you’ll create a .NET Core console application project. The project type comes with all the template files you’ll need, before you’ve even added anything!

Open Visual Studio.

If the start window is not open, choose File > Start Window.

On the start window, choose Create a new project.

On the Create a new project window, enter or type console in the search box. Next, choose C# from the Language list, and then choose Windows from the Platform list.

After you apply the language and platform filters, choose the Console Application template for .NET Core, and then choose Next.

Screenshot of the C# template for the Console App.

[!NOTE] If you do not see the Console App template, you can install it from the Create a new project window. In the Not finding what you’re looking for? message, choose the Install more tools and features link. Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.

In the Configure your new project window, type or enter GetStartedDebugging in the Project name box. Then, choose Next.

Choose either the recommended target framework (.NET Core 3.1 (Long-term support)) or .NET 5.0 (Current) , and then choose Create.

Visual Studio opens your new project.

Open Visual Studio. If the start window isn’t open, choose File > Start Window.

On the start window, choose Create a new project.

On the Create a new project window, enter or type console in the search box. Next, choose C# from the Language list, and then choose Windows from the Platform list.

After you apply the language and platform filters, choose the Console Application template, and then choose Next.

. image type=»content» source=»media/vs-2022/get-started-create-console-project.png» alt-text=»Screenshot of the ‘Console Application’ template in the ‘Create a new project’ window of Visual Studio 2022.».

[!NOTE] If you don’t see the Console Application template, you can install it from the Create a new project window. In the Not finding what you’re looking for? message, choose the Install more tools and features link. Then, in the Visual Studio Installer, choose the .NET desktop development workload.

In the Configure your new project window, type or enter GetStartedDebugging in the Project name box. Then, choose Next.

In the Additional information window, ensure that .NET 6.0 (Long-term support) is selected in the Framework dropdown menu, and then choose Create.

Visual Studio opens your new project.

Create the application

In Program.cs, replace all of the default code with the following code:

Start the debugger!

Image of the

Press F5 (Debug > Start Debugging) or the Start Debugging button in the Debug Toolbar.

F5 starts the app with the debugger attached to the app process, but right now we haven’t done anything special to examine the code. So the app just loads and you’ll see this console output.

In this tutorial, we’ll take a closer look at this app using the debugger and get a look at the debugger features.

Image of the

Stop the debugger by pressing the red stop button (Shift + F5).

In the console window, press a key to close the console window.

Mostly, we use keyboard shortcuts here, because it’s a fast way to execute debugger commands. Equivalent commands, such as toolbar or menu commands, are also noted.

To start the debugger, select F5, or choose the Debug Target button in the Standard toolbar, or choose the Start Debugging button in the Debug toolbar, or choose Debug > Start Debugging from the menu bar.

. image type=»content» source=»media/vs-2022/dbg-tour-start-debugging.png» alt-text=»Screenshot of the ‘Debug Target’ button in the Standard toolbar of Visual Studio 2022.».

F5 starts the app with the debugger attached to the app process. Since we haven’t done anything special to examine the code, the app runs to completion and you see the console output.

To stop the debugger, select Shift+F5, or choose the Stop Debugging button in the Debug toolbar, or choose Debug > Stop Debugging from the menu bar.

. image type=»content» source=»media/vs-2022/dbg-tour-stop-debugging.png» alt-text=»Screenshot of the ‘Stop debugging’ button in the Debug toolbar of Visual Studio 2022.».

In the console window, select any key to close the console window.

Set a breakpoint and start the debugger

In the for loop of the Main function, set a breakpoint by clicking the left margin of the following line of code:

Image of a breakpoint.

A red circle appears where you set the breakpoint.

Breakpoints are one of the most basic and essential features of reliable debugging. A breakpoint indicates where Visual Studio should suspend your running code so you can take a look at the values of variables, or the behavior of memory, or whether or not a branch of code is getting run.

Screenshot of the

Press F5 or the Start Debugging button , the app starts, and the debugger runs to the line of code where you set the breakpoint.

The yellow arrow represents the statement on which the debugger paused, which also suspends app execution at the same point (this statement has not yet executed).

If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. Otherwise, F5 continues running the app to the next breakpoint.

Breakpoints are a useful feature when you know the line of code or the section of code that you want to examine in detail. For information on the different types of breakpoints you can set, such as conditional breakpoints, see Using breakpoints.

In the for loop of the Main function, set a breakpoint by clicking the left margin of the following line of code:

A red circle appears where you set the breakpoint.

. image type=»content» source=»media/vs-2022/dbg-tour-breakpoint.png» alt-text=»Screenshot of a breakpoint in Visual Studio 2022.».

Breakpoints are an essential feature of reliable debugging. You can set breakpoints where you want Visual Studio to pause your running code so you can look at the values of variables or the behavior of memory, or know whether or not a branch of code is getting run.

To start debugging, select F5, or choose the Debug Target button in the Standard toolbar, or choose the Start Debugging button in the Debug toolbar, or choose Debug > Start Debugging from the menu bar. The app starts and the debugger runs to the line of code where you set the breakpoint.

. image type=»content» source=»media/vs-2022/get-started-set-breakpoint.png» alt-text=»Screenshot showing a breakpoint in the code editor of Visual Studio 2022, with code execution paused at the breakpoint.».

The yellow arrow points to the statement on which the debugger paused. App execution is paused at the same point, with the statement not yet executed.

When the app isn’t running, F5 will start the debugger, which will run the app until it reaches the first breakpoint. If the app is paused at a breakpoint, then F5 will continue running the app until it reaches the next breakpoint.

Breakpoints are a useful feature when you know the line or section of code that you want to examine in detail. For more about the different types of breakpoints you can set, such as conditional breakpoints, see Using breakpoints.

Navigate code and inspect data by using data tips

Mostly, we use the keyboard shortcuts here, because it’s a good way to get fast at executing your app in the debugger (equivalent commands such as menu commands are shown in parentheses).

While paused on the name += letters[i] statement, hover over the letters variable and you see it’s default value, the value of the first element in the array, char[10] .

Features that allow you to inspect variables are one of the most useful features of the debugger, and there are different ways to do it. Often, when you try to debug an issue, you are attempting to find out whether variables are storing the values that you expect them to have at a particular time.

Expand the letters variable to see its properties, which include all the elements that the variable contains.

Screenshot of the debugger paused at the

Next, hover over the name variable, and you see its current value, an empty string.

Press F10 (or choose Debug > Step Over) twice to advance to the SendMessage method call, and then press F10 one more time.

F10 advances the debugger to the next statement without stepping into functions or methods in your app code (the code still executes). By pressing F10 on the SendMessage method call, we skipped over the implementation code for SendMessage (which maybe we’re not interested in right now).

Press F10 (or Debug > Step Over) a few times to iterate several times through the for loop, pausing again at the breakpoint, and hovering over the name variable each time to check its value.

The value of the variable changes with each iteration of the for loop, showing values of f , then fr , then fre , and so on. To advance the debugger through the loop faster in this scenario, you can press F5 (or choose Debug > Continue) instead, which advances you to the breakpoint instead of the next statement.

Often, when debugging, you want a quick way to check property values on variables, to see whether they are storing the values that you expect them to store, and the data tips are a good way to do it.

While still paused in the for loop in the Main method, press F11 (or choose Debug > Step Into) until you pause at the SendMessage method call.

You should be at this line of code:

Press F11 one more time to step into the SendMessage method.

The yellow pointer advances into the SendMessage method.

Screenshot of the execution pointer at the SendMessage method.

F11 is the Step Into command and advances the app execution one statement at a time. F11 is a good way to examine the execution flow in the most detail. By default, the debugger skips over non-user code (if you want more details, see Just My Code).

Let’s say that you are done examining the SendMessage method, and you want to get out of the method but stay in the debugger. You can do this using the Step Out command.

Press Shift + F11 (or Debug > Step Out).

This command resumes app execution (and advances the debugger) until the current method or function returns.

You should be back in the for loop in the Main method, paused at the SendMessage method call. For more information on different ways to move through your code, see Navigate code in the debugger.

While paused on the name += letters[i] statement, hover over the letters variable to see a data tip showing the array size and element type, char[10] .

[!NOTE] One of the most useful features of the debugger is its ability to inspect a variable. Often, when you’re trying to debug an issue, you’re attempting to find out whether variables have values that you expect at a particular time. Viewing data tips is a good way to check that.

Expand the letters variable to view all its array elements and their values.

. image type=»content» source=»media/vs-2022/get-started-view-data-tip.png» alt-text=»Screenshot of a debugger data tip in Visual Studio 2022 that shows the element values for the ‘letters’ array variable.».

Hover over the name variable to see its current value, which is an empty string.

To advance the debugger to the next statement, select F10, or choose the Step Over button in the Debug toolbar, or choose Debug > Step Over from the menu bar. Select F10 twice more to move past the SendMessage method call.

F10 advances the debugger without stepping into function or methods, although their code still executes. In this way, we skipped debugging the code in the SendMessage method, which we’re not interested in right now.

To iterate through the for loop a few times, select F10 repeatedly. During each loop iteration, pause at the breakpoint, and then hover over the name variable to check its value in the data tip.

. image type=»content» source=»media/vs-2022/get-started-data-tip.png» alt-text=»Screenshot of a debugger data tip in Visual Studio 2022 that shows the string value for the ‘name’ variable.».

The value of the variable changes with each iteration of the for loop, showing values of f , then fr , then fre , and so on. To advance the debugger through the loop faster, select F5 instead, which advances to your breakpoint instead of the next statement.

While paused in the for loop of the Main method, select F11, or choose the Step Into button from the Debug toolbar, or choose Debug > Step Into from the menu bar, until you reach the SendMessage method call.

The debugger should be paused at this line of code:

To step into the SendMessage method, select F11 again.

The yellow pointer advances into the SendMessage method.

. image type=»content» source=»media/vs-2022/get-started-f11.png» alt-text=»Screenshot showing the execution pointer of the debugger within the ‘SendMessage’ method.».

F11 helps you examine the execution flow of your code in more depth. To step into a method from a method call, select F11. By default, the debugger skips stepping into non-user methods. To learn about debugging non-user code, see Just My Code.

Once you’ve finished debugging the SendMessage method, you’re ready to return to the for loop of the main method.

To leave the SendMessage method, select Shift+F11, or choose the Step Out button in the Debug toolbar, or choose Debug > Step Out from the menu bar.

Step Out resumes app execution and advances the debugger until the current method or function returns.

You’ll see the yellow pointer back in the for loop of the Main method, paused at the SendMessage method call. For more information on different ways to move through your code, see Navigate code in the debugger.

Navigate code using Run to Click

Select F5 to advance to the breakpoint again.

Image of the

In the code editor, scroll down and hover over the Console.WriteLine method in the SendMessage method until the green Run to Click button appears on the left. The tooltip for the button shows «Run execution to here».

Screenshot of the

[!NOTE] The Run to Click button is new in [!includevs_dev15]. (If you don’t see the green arrow button, use F11 in this example instead to advance the debugger to the right place.)

Image of the

Click the Run to Click button .

The debugger advances to the Console.WriteLine method.

Using this button is similar to setting a temporary breakpoint. Run to Click is handy for getting around quickly within a visible region of app code (you can click in any open file).

Select F5 to advance to the breakpoint again.

In the code editor, hover over the Console.WriteLine method call in the SendMessage method until the Run to Click button appears on the left. The tooltip for the button shows «Run execution to here».

. image type=»content» source=»media/vs-2022/get-started-run-to-click.png» alt-text=»Screenshot showing the ‘Run to Click’ button in Visual Studio 2022.».

Choose the Run to Click button. Alternatively, with your cursor at the Console.WriteLine statement, select Ctrl+F10. Or, right-click the Console.WriteLine method call, and choose Run to Cursor from the context menu.

The debugger advances to the Console.WriteLine method call.

Using the Run to Click button is similar to setting a temporary breakpoint, and is handy for getting around quickly within a visible region of your app code in an open file.

Restart your app quickly

Image of the

Click the Restart button in the Debug Toolbar (Ctrl + Shift + F5).

When you press Restart, it saves time versus stopping the app and restarting the debugger. The debugger pauses at the first breakpoint that is hit by executing code.

The debugger stops again at the breakpoint you previously set inside the for loop.

To rerun your app from the beginning in the debugger, select Ctrl+Shift+F5, or choose the Restart button in the Debug toolbar, or choose Debug > Restart from the menu bar.

. image type=»content» source=»media/vs-2022/dbg-tour-restart-debugging.png» alt-text=»Screenshot of the ‘Restart’ button in the Debug toolbar of Visual Studio 2022.».

Restart stops the debugger and then restarts it, in one step. When the debugger restarts, it will run to the first breakpoint, which is the breakpoint you previously set inside the for loop, and then pause.

Inspect variables with the Autos and Locals windows

Look at the Autos window at the bottom of the code editor.

If it is closed, open it while paused in the debugger by choosing Debug > Windows > Autos.

In the Autos window, you see variables and their current value. The Autos window shows all variables used on the current line or the preceding line (Check documentation for language-specific behavior).

Next, look at the Locals window, in a tab next to the Autos window.

Expand the letters variable to show the elements that it contains.

Screenshot of the Locals Window in Visual Studio.

The Locals window shows you the variables that are in the current scope, that is, the current execution context.

The Autos and Locals windows show variable values while you’re debugging. The windows are only available during a debug session. The Autos window shows variables used on the current line that the debugger is at and the preceding line. The Locals window shows variables defined in the local scope, which is usually the current function or method.

While the debugger is paused, view the Autos window at the bottom of the code editor.

If the Autos window is closed, select Ctrl+D, A, or choose Debug > Windows > Autos from the menu bar.

With the debugger still paused, view the Locals window, in a tab next to the Autos window.

If the Locals window is closed, select Ctrl+D, L, or choose Debug > Windows > Locals.

In the Locals window, expand the letters variable to see its array elements and their values.

. image type=»content» source=»media/vs-2022/get-started-locals-window.png» alt-text=»Screenshot of the Locals window in Visual Studio 2022, with the ‘letters’ array variable expanded.».

For more about the Autos and Locals windows, see Inspect variables in the Autos and Locals windows.

In the main code editor window, right-click the name variable and choose Add Watch.

The Watch window opens at the bottom of the code editor. You can use a Watch window to specify a variable (or an expression) that you want to keep an eye on.

Now, you have a watch set on the name variable, and you can see its value change as you move through the debugger. Unlike the other variable windows, the Watch window always shows the variables that you are watching (they’re grayed out when out of scope).

You can specify a variable, or an expression, that you want to keep an eye on as you step through code—by adding it to the Watch window.

While the debugger is paused, right-click the name variable and choose Add Watch.

The Watch window opens by default at the bottom of the code editor.

Now that you’ve set a watch on the name variable, step through your code to see the value of the name variable change with each for loop iteration.

Unlike the other variable windows, the Watch window always shows the variables that you’re watching, though they’ll be grayed out when they’re out of scope.

For more about the Watch window, see Watch variables with Watch windows.

Examine the call stack

While paused in the for loop, click the Call Stack window, which is by default open in the lower right pane.

If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack.

Click F11 a few times until you see the debugger pause in the SendMessage method. Look at the Call Stack window.

Screenshot of the Call Stack window in Visual Studio.

The Call Stack window shows the order in which methods and functions are getting called. The top line shows the current function (the SendMessage method in this app). The second line shows that SendMessage was called from the Main method, and so on.

[!NOTE] The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.

The call stack is a good way to examine and understand the execution flow of an app.

You can double-click a line of code to go look at that source code and that also changes the current scope being inspected by the debugger. This action does not advance the debugger.

You can also use right-click menus from the Call Stack window to do other things. For example, you can insert breakpoints into specified functions, advance the debugger using Run to Cursor, and go examine source code. For more information, see How to: Examine the Call Stack.

The Call Stack can help you understand the execution flow of your app, by showing the order in which methods and functions are getting called.

While the debugger is paused in the for loop, view the Call Stack window, which opens by default in the lower right pane of the code editor.

If the Call Stack window is closed, select Ctrl+D, C, or choose Debug > Windows > Call Stack from the menu bar.

In the Call Stack window, you’ll see the yellow pointer at the current Main method.

Select F11 a few times until you see the debugger pause in the SendMessage method.

The top line of the Call Stack window shows the current function, which is the SendMessage method. The second line shows that the SendMessage method was called from the Main method.

. image type=»content» source=»media/vs-2022/get-started-call-stack.png» alt-text=»Screenshot of the Call Stack window in Visual Studio 2022.».

[!NOTE] The Call Stack window is similar to the Debug perspective in some IDEs, like Eclipse.

In the Call Stack window, you can double-click a line of code to go to that source code, which changes the current scope being inspected by the debugger. This action does not advance the debugger.

You can also use right-click menus from the Call Stack window to do other things. For example, you can insert breakpoints into specified functions, advance the debugger by using Run to Cursor, or go to source code.

For more about the Call Stack, see How to: Examine the Call Stack.

Change the execution flow

Press F11 twice to run the Console.WriteLine method.

With the debugger paused in the SendMessage method call, use the mouse to grab the yellow arrow (the execution pointer) on the left and move the yellow arrow up one line, back to Console.WriteLine .

Press F11.

The debugger reruns the Console.WriteLine method (you see this in the console window output).

By changing the execution flow, you can do things like test different code execution paths or rerun code without restarting the debugger.

[!WARNING] Often you need to be careful with this feature, and you see a warning in the tooltip. You may see other warnings, too. Moving the pointer cannot revert your application to an earlier app state.

Press F5 to continue running the app.

Congratulations on completing this tutorial!

You can move the execution pointer to change the flow of your app while debugging.

With the debugger paused at the SendMessage method call in the for loop, select F11 three times to step into the SendMessage method and to move past the Console.WriteLine method after executing it.

The debugger is now paused at the final closing brace of the SendMessage method.

Use the mouse to grab the yellow arrow or execution pointer (in the left margin), and then drag the pointer up one line.

The debugger is now back on the Console.WriteLine statement.

Select F11.

The debugger reruns the Console.WriteLine method, and you’ll see a duplicate line in the console window output.

Select F5 to continue running the app.

By changing the execution flow, you can do things like test different code execution paths or rerun code without restarting the debugger.

[!WARNING] Use this feature with care. You’ll see a warning in the tooltip of the execution pointer about the possibility of unintended consequences. You might see other warnings, too. Moving the execution pointer can’t revert your application to an earlier state.

For more about the changing the execution flow, see Move the pointer to change the execution flow.

Congratulations on completing this tutorial!

In this tutorial, you’ve learned how to start the debugger, step through code, and inspect variables. You might want to get a high-level look at debugger features along with links to more information.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *