Tools visual studio где находится
Visual Studio 2012 Ultimate, вот тут его тоже нет
но вот так его можно добавить
P.S. Document Outline = Структура документа
- Предложено в качестве ответа Medet Tleukabiluly 22 декабря 2013 г. 6:24
- Помечено в качестве ответа Maksim Marinov Microsoft contingent staff, Moderator 26 декабря 2013 г. 8:25
Все ответы
- Предложено в качестве ответа V.A.Zolotov 21 декабря 2013 г. 5:32
Нет, я не про панель элементов, а про "Структура документа".
У меня вот такое:
А должно быть вот так:
Я так и не понял почему так, раньше все было нормально. После обновления ОС, заново переустановил студию и такая вот стала ерунда 🙁
Tools visual studio где находится
Это окно содержит Windows Forms компоненты, которые вы можете разместить на своей форме. Если такого окна в вашем Visual Studio нет, выберите в главном меню пункт View/Toolbox (рис. 1.8). Окно визуально отображает наиболее часто используемые .NET компоненты для создания приложений Windows. Toolbox имеет несколько закладок: Data, Components, Windows Forms, General и др. Все содержат компоненты, которые можно перетянуть мышью на форму. Закладка Windows Forms включает визуальные элементы управления, такие как кнопки, списки, деревья. Закладка Data посвящена базам данных. Закладка Components содержит невизуальные компоненты, наиболее представительным среди которых является Timer. В закладку General вы можете добавить любой элемент из другой закладки простым перетаскиванием.
Рис. 1.8. Инструментальная панель (Toolbox).
1.6. Визуальные свойства вспомогательных окон.
Нельзя не отметить некоторые свойства всех вышеописанных окон. Во-первых, все они могут «прилипать» к любой стороне главного окна Visual Studio. Во-вторых, прятаться при потере активности. Для того чтобы наделить этим свойством, например, Solution Explorer, выберите в контекстном меню этого окна пункт Auto Hide (рис. 1.9.) или нажмите соответствующую кнопку рядом с кнопкой заголовка «Закрыть».
Рис. 1.9. Режим автоматического исчезновения окна с экрана.
Рис. 1.10. Панель отображения скрытых окон.
Сейчас, если Solution Ехрlorer потеряет активность (например, вы сделаете активной форму), тогда его окно спрячется в прилежащую панель (рис. 1.10). Чтобы вернуть окно в первоначальное состояние, просто щелкните левой кнопкой мыши по соответствующему названию в панели.
1.7. Меню и панель инструментов среды Visual Studio 2005.
Все действия, которые вы можете выполнять в среде Visual Studio 2005, располагаются в главном меню. Главное меню имеет контекстную зависимость от текущего состояния среды, то есть содержит различные пункты в зависимости от того, чем вы сейчас занимаетесь и в каком окне находитесь. Кроме того, большинство пунктов меню продублированы в панели инструментов. Visual Studio 2005 имеет множество панелей инструментов. Вы можете включить или выключить панель инструментов при помощи меню View/Toolbars (рис. 1.11).
Рис. 1.11. Настройка панели инструментов.
Те панели инструментов, которые уже открыты, помечены в меню «галочками». Вы также можете создавать собственные панели инструментов, воспользовавшись пунктом этого же меню Customize.
Главное меню Visual Studio 2005 находится в верхней части среды. В меню есть все команды, предназначенные для выполнения действий над элементами проектов Visual Studio 2005 . Пункты меню бывают командными и всплывающими (содержащими другие пункты меню). Название каждого всплывающего пункта меню отражает содержащиеся в нем команды. Например, меню «File» содержит команды, предназначенные для работы с файлами проекта. Некоторые пункты меню включают вложенные пункты с более подробными командами. Например, команда «New» из меню «File» показывает меню выбора типов файлов. Наиболее часто употребляемые пункты меню имеют «горячие» клавиши. Так, для создания нового файла нужно нажать клавиши CTRL+N.
User Interface
At its heart, Visual Studio Code is a code editor. Like many other code editors, VS Code adopts a common user interface and layout of an explorer on the left, showing all of the files and folders you have access to, and an editor on the right, showing the content of the files you have opened.
Basic Layout
VS Code comes with a simple and intuitive layout that maximizes the space provided for the editor while leaving ample room to browse and access the full context of your folder or project. The UI is divided into five areas:
- Editor — The main area to edit your files. You can open as many editors as you like side by side vertically and horizontally.
- Side Bar — Contains different views like the Explorer to assist you while working on your project.
- Status Bar — Information about the opened project and the files you edit.
- Activity Bar — Located on the far left-hand side, this lets you switch between views and gives you additional context-specific indicators, like the number of outgoing changes when Git is enabled.
- Panels — You can display different panels below the editor region for output or debug information, errors and warnings, or an integrated terminal. Panel can also be moved to the right for more vertical space.
Each time you start VS Code, it opens up in the same state it was in when you last closed it. The folder, layout, and opened files are preserved.
Open files in each editor are displayed with tabbed headers (Tabs) at the top of the editor region. To learn more about tabbed headers, see the Tabs section below.
Tip: You can move the Side Bar to the right hand side (View > Move Side Bar Right) or toggle its visibility ( ⌘B (Windows, Linux Ctrl+B ) ).
Side by side editing
You can open as many editors as you like side by side vertically and horizontally. If you already have one editor open, there are multiple ways of opening another editor to the side of the existing one:
- Alt click on a file in the Explorer.
- ⌘\ (Windows, Linux Ctrl+\ ) to split the active editor into two.
- Open to the Side ( ⌃Enter (Windows, Linux Ctrl+Enter ) ) from the Explorer context menu on a file.
- Click the Split Editor button in the upper right of an editor.
- Drag and drop a file to any side of the editor region.
- Ctrl+Enter (macOS: Cmd+Enter ) in the Quick Open ( ⌘P (Windows, Linux Ctrl+P ) ) file list.
Whenever you open another file, the editor that is active will display the content of that file. So if you have two editors side by side and you want to open file ‘foo.cs’ into the right-hand editor, make sure that editor is active (by clicking inside it) before opening file ‘foo.cs’.
By default editors will open to the right-hand side of the active one. You can change this behavior through the setting workbench.editor.openSideBySideDirection and configure to open new editors to the bottom of the active one instead.
When you have more than one editor open you can switch between them quickly by holding the Ctrl (macOS: Cmd ) key and pressing 1 , 2 , or 3 .
Tip: You can resize editors and reorder them. Drag and drop the editor title area to reposition or resize the editor.
Minimap
A Minimap (code outline) gives you a high-level overview of your source code, which is useful for quick navigation and code understanding. A file’s minimap is shown on the right side of the editor. You can click or drag the shaded area to quickly jump to different sections of your file.
Tip: You can move the minimap to the left hand side or disable it completely by respectively setting "editor.minimap.side": "left" or "editor.minimap.enabled": false in your user or workspace settings.
Indent Guides
The image above also shows indentation guides (vertical lines) which help you quickly see matching indent levels. If you would like to disable indent guides, you can set "editor.guides.indentation": false in your user or workspace settings.
Breadcrumbs
The editor has a navigation bar above its contents called Breadcrumbs. It shows the current location and allows you to quickly navigate between folders, files, and symbols.
Breadcrumbs always show the file path and if the current file type has language support for symbols, the symbol path up to the cursor position. You can disable breadcrumbs with the View > Show Breadcrumbs toggle command. For more information about the breadcrumbs feature, such as how to customize their appearance, see the Breadcrumbs section of the Code Navigation article.
Explorer
The Explorer is used to browse, open, and manage all of the files and folders in your project. VS Code is file and folder based — you can get started immediately by opening a file or folder in VS Code.
After opening a folder in VS Code, the contents of the folder are shown in the Explorer. You can do many things from here:
- Create, delete, and rename files and folders.
- Move files and folders with drag and drop.
- Use the context menu to explore all options.
Tip: You can drag and drop files into the Explorer from outside VS Code to copy them (if the explorer is empty VS Code will open them instead)
VS Code works very well with other tools that you might use, especially command-line tools. If you want to run a command-line tool in the context of the folder you currently have open in VS Code, right-click the folder and select Open in Command Prompt (or Open in Terminal on macOS or Linux).
You can also navigate to the location of a file or folder in the native Explorer by right-clicking on a file or folder and selecting Reveal in Explorer (or Reveal in Finder on macOS or Open Containing Folder on Linux).
Tip: Type ⌘P (Windows, Linux Ctrl+P ) (Quick Open) to quickly search and open a file by its name.
By default, VS Code excludes some folders from the Explorer (for example. .git ). Use the files.exclude setting to configure rules for hiding files and folders from the Explorer.
Tip: This is really useful to hide derived resources files, like \*.meta in Unity, or \*.js in a TypeScript project. For Unity to exclude the \*.cs.meta files, the pattern to choose would be: "**/*.cs.meta": true . For TypeScript, you can exclude generated JavaScript for TypeScript files with: "**/*.js": .
Multi-selection
You can select multiple files in the File Explorer and OPEN EDITORS view to run actions (Delete, Drag and Drop, Open to the Side) on multiple items. Use the Ctrl/Cmd key with click to select individual files and Shift + click to select a range. If you select two items, you can now use the context menu Compare Selected command to quickly diff two files.
Note: In earlier VS Code releases, clicking with the Ctrl/Cmd key pressed would open a file in a new Editor Group to the side. If you would still like this behavior, you can use the workbench.list.multiSelectModifier setting to change multi-selection to use the Alt key.
Advanced tree navigation
You can filter the currently visible files in the File Explorer. With the focus on the File Explorer, press Ctrl/Cmd+F to open the tree Find control and type part of the file name you want to match. You will see a Find control in the top-right of the File Explorer showing what you have typed and matching file names will be highlighted. Pressing the Filter button will toggle between the two modes: highlighting and filtering. Pressing DownArrow will let you focus the first matched element and jump between matching elements.
This navigation feature is available for all tree views in VS Code, so feel free to try it out in other areas of the product.
Outline view
The Outline view is a separate section in the bottom of the File Explorer. When expanded, it will show the symbol tree of the currently active editor.
The Outline view has different Sort By modes, optional cursor tracking, and supports the usual open gestures. It also includes an input box which finds or filters symbols as you type. Errors and warnings are also shown in the Outline view, letting you see at a glance a problem’s location.
For symbols, the view relies on information computed by your installed extensions for different file types. For example, the built-in Markdown support returns the Markdown header hierarchy for a Markdown file’s symbols.
There are several Outline view settings which allow you to enable/disable icons and control the errors and warnings display (all enabled by default):
- outline.icons — Toggle rendering outline elements with icons.
- outline.problems.enabled — Show errors and warnings on outline elements.
- outline.problems.badges — Toggle using badges for errors and warnings.
- outline.problems.colors — Toggle using colors for errors and warnings.
Open Editors
At the top of the Explorer is a view labeled OPEN EDITORS. This is a list of active files or previews. These are files you previously opened in VS Code that you were working on. For example, a file will be listed in the OPEN EDITORS view if you:
- Make a change to a file.
- Double-click a file’s header.
- Double-click a file in the Explorer.
- Open a file that is not part of the current folder.
Just click an item in the OPEN EDITORS view, and it becomes active in VS Code.
Once you are done with your task, you can remove files individually from the OPEN EDITORS view, or you can remove all files by using the View: Close All Editors or View: Close All Editors in Group actions.
Views
The File Explorer is just one of the Views available in VS Code. There are also Views for:
- Search — Provides global search and replace across your open folder.
- Source Control — VS Code includes Git source control by default.
- Run — VS Code’s Run and Debug View displays variables, call stacks, and breakpoints.
- Extensions — Install and manage your extensions within VS Code.
- Custom views — Views contributed by extensions.
Tip: You can open any view using the View: Open View command.
You can show or hide views from within the main view and also reorder them by drag and drop.
Activity Bar
The Activity Bar on the left lets you quickly switch between Views. You can also reorder Views by dragging and dropping them on the Activity Bar or remove a View entirely (right click Hide from Activity Bar).
Command Palette
VS Code is equally accessible from the keyboard. The most important key combination to know is ⇧⌘P (Windows, Linux Ctrl+Shift+P ) , which brings up the Command Palette. From here, you have access to all of the functionality of VS Code, including keyboard shortcuts for the most common operations.
The Command Palette provides access to many commands. You can execute editor commands, open files, search for symbols, and see a quick outline of a file, all using the same interactive window. Here are a few tips:
- ⌘P (Windows, Linux Ctrl+P ) will let you navigate to any file or symbol by typing its name
- ⌃Tab (Windows, Linux Ctrl+Tab ) will cycle you through the last set of files opened
- ⇧⌘P (Windows, Linux Ctrl+Shift+P ) will bring you directly to the editor commands
- ⇧⌘O (Windows, Linux Ctrl+Shift+O ) will let you navigate to a specific symbol in a file
- ⌃G (Windows, Linux Ctrl+G ) will let you navigate to a specific line in a file
Type ? into the input field to get a list of available commands you can execute from here:
Configuring the editor
VS Code gives you many options to configure the editor. From the View menu, you can hide or toggle various parts of the user interface, such as the Side Bar, Status Bar, and Activity Bar.
Hide the Menu Bar (Windows, Linux)
You can hide the Menu Bar on Windows and Linux by changing the setting window.menuBarVisibility from classic to toggle . A setting of toggle means that a single press of the Alt key will show the Menu Bar again.
You can also hide the Menu Bar on Windows and Linux with the View > Toggle Menu Bar command. This command sets window.menuBarVisibility from classic to compact , resulting in the Menu Bar moving into the Activity Bar. To return the Menu Bar to the classic position, you can execute the View > Toggle Menu Bar command again.
Settings
Most editor configurations are kept in settings which can be modified directly. You can set options globally through user settings or per project/folder through workspace settings. Settings values are kept in a settings.json file.
- Select File > Preferences > Settings (or press ⌘, (Windows, Linux Ctrl+, ) ) to edit the user settings.json file.
- To edit workspace settings, select the WORKSPACE SETTINGS tab to edit the workspace settings.json file.
Note for macOS users: The Preferences menu is under Code not File. For example, Code > Preferences > Settings.
You will see the VS Code Default Settings in the left window and your editable settings.json on the right. You can easily filter settings in the Default Settings using the search box at the top. Copy a setting over to the editable settings.json on the right by clicking on the edit icon to the left of the setting. Settings with a fixed set of values allow you to pick a value as part of their edit icon menu.
After editing your settings, type ⌘S (Windows, Linux Ctrl+S ) to save your changes. The changes will take effect immediately.
Note: Workspace settings will override User settings and are useful for sharing project specific settings across a team.
Zen Mode
Zen Mode lets you focus on your code by hiding all UI except the editor (no Activity Bar, Status Bar, Side Bar and Panel), going to full screen and centering the editor layout. Zen mode can be toggled using View menu, Command Palette or by the shortcut ⌘K Z (Windows, Linux Ctrl+K Z ) . Double Esc exits Zen Mode. The transition to full screen can be disabled via zenMode.fullScreen . Zen Mode can be further tuned by the following settings: zenMode.hideStatusBar , zenMode.hideTabs , zenMode.fullScreen , zenMode.restore , and zenMode.centerLayout .
Centered editor layout
Centered editor layout allows you to center align the editor area. This is particularly useful when working with a single editor on a large monitor. You can use the sashes on the side to resize the view (hold down the Alt key to independently move the sashes).
Visual Studio Code shows open items with Tabs (tabbed headings) in the title area above the editor.
When you open a file, a new Tab is added for that file.
Tabs let you quickly navigate between items and you can Drag and Drop Tabs to reorder them.
When you have more open items than can fit in the title area, you can use the Show Opened Editors command (available through the . More button) to display a dropdown list of tabbed items.
If you don’t want to use Tabs, you can disable the feature by setting the workbench.editor.showTabs setting to false:
See the section below to optimize VS Code when working without Tabs.
Tab ordering
By default, new Tabs are added to the right of the existing Tabs but you can control where you’d like new Tabs to appear with the workbench.editor.openPositioning setting.
For example, you might like new tabbed items to appear on the left:
Preview mode
When you single-click or select a file in the Explorer, it is shown in a preview mode and reuses an existing Tab. This is useful if you are quickly browsing files and don’t want every visited file to have its own Tab. When you start editing the file or use double-click to open the file from the Explorer, a new Tab is dedicated to that file.
Preview mode is indicated by italics in the Tab heading:
If you’d prefer to not use preview mode and always create a new Tab, you can control the behavior with these settings:
- workbench.editor.enablePreview to globally enable or disable preview editors
- workbench.editor.enablePreviewFromQuickOpen to enable or disable preview editors when opened from Quick Open
Editor Groups
When you split an editor (using the Split Editor or Open to the Side commands), a new editor region is created which can hold a group of items. You can open as many editor regions as you like side by side vertically and horizontally.
You can see these clearly in the OPEN EDITORS section at the top of the Explorer view:
You can Drag and Drop editor groups on the workbench, move individual Tabs between groups and quickly close entire groups (Close All).
Note: VS Code uses editor groups whether or not you have enabled Tabs. Without Tabs, editor groups are a stack of your open items with the most recently selected item visible in the editor pane.
Grid editor layout
By default, editor groups are laid out in vertical columns (for example when you split an editor to open it to the side). You can easily arrange editor groups in any layout you like, both vertically and horizontally:
To support flexible layouts, you can create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can change this behavior with the new setting workbench.editor.closeEmptyGroups: false :
There are a predefined set of editor layouts in the new View > Editor Layout menu:
Editors that open to the side (for example by clicking the editor toolbar Split Editor action) will by default open to the right-hand side of the active editor. If you prefer to open editors below the active one, configure the new setting workbench.editor.openSideBySideDirection: down .
There are many keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is a fast way to split the editor into any direction:
Pro Tip: If you press and hold the Alt key while hovering over the toolbar action to split an editor, it will offer to split to the other orientation. This is a fast way to split either to the right or to the bottom.
Keyboard shortcuts
Here are some handy keyboard shortcuts to quickly navigate between editors and editor groups.
If you’d like to modify the default keyboard shortcuts, see Key Bindings for details.
- ⌥⌘→ (Windows, Linux Ctrl+PageDown ) go to the right editor.
- ⌥⌘← (Windows, Linux Ctrl+PageUp ) go to the left editor.
- ⌃Tab (Windows, Linux Ctrl+Tab ) open the previous editor in the editor group MRU list.
- ⌘1 (Windows, Linux Ctrl+1 ) go to the leftmost editor group.
- ⌘2 (Windows, Linux Ctrl+2 ) go to the center editor group.
- ⌘3 (Windows, Linux Ctrl+3 ) go to the rightmost editor group.
- ⌘W (Windows, Linux Ctrl+W ) close the active editor.
- ⌘K W (Windows, Linux Ctrl+K W ) close all editors in the editor group.
- ⌘K ⌘W (Windows, Linux Ctrl+K Ctrl+W ) close all editors.
Working without Tabs
If you prefer not to use Tabs (tabbed headings), you can disable Tabs (tabbed headings) entirely by setting workbench.editor.showTabs to false.
Disable Preview mode
Without Tabs, the OPEN EDITORS section of the File Explorer is a quick way to do file navigation. With preview editor mode, files are not added to the OPEN EDITOR list nor editor group on single-click open. You can disable this feature through the workbench.editor.enablePreview and workbench.editor.enablePreviewFromQuickOpen settings.
Ctrl+Tab to navigate in entire editor history
You can change keybindings for Ctrl+Tab to show you a list of all opened editors from the history independent from the active editor group.
Edit your keybindings and add the following:
Close an entire group instead of a single editor
If you liked the behavior of VS Code closing an entire group when closing one editor, you can bind the following in your keybindings.
Window management
VS Code has some options to control how windows (instances) should be opened or restored between sessions.
The settings window.openFoldersInNewWindow and window.openFilesInNewWindow are provided to configure opening new windows or reusing the last active window for files or folders and possible values are default , on and off .
If configured to be default , we will make the best guess about reusing a window or not based on the context from where the open request was made. Flip this to on or off to always behave the same. For example, if you feel that picking a file or folder from the File menu should always open into a new window, set this to on .
Note: There can still be cases where this setting is ignored (for example, when using the -new-window or -reuse-window command-line option).
The window.restoreWindows setting tells VS Code how to restore the opened windows of your previous session. By default, VS Code will restore all windows you worked on during your previous session (setting: all ). Change this setting to none to never reopen any windows and always start with an empty VS Code instance. Change it to one to reopen the last opened window you worked on or folders to only restore windows that had folders opened.
Next steps
Now that you know the overall layout of VS Code, start to customize the editor to how you like to work by looking at the following topics:
Изучаем Visual Studio .NET. Часть 1. Знакомство со средой разработки
Выпущенное в этом году корпорацией Microsoft новое средство разработки Microsoft Visual Studio .NET открывает широкие возможности разработки приложений для платформы Microsoft .NET, включая создание Windows- и Web-приложений, а также корпоративных приложений нового поколения, в том числе основанных на применении Web-сервисов XML.
В настоящей статье мы начнем знакомство со средой разработки Visual Studio .NET и рассмотрим некоторые новые возможности этого продукта.
Настройка среды разработки
Cреда разработки Visual Studio .NET, как и среды всех современных средств разработки, может быть настроена согласно потребностям конкретного пользователя.
В этом разделе мы рассмотрим различные способы настройки среды Visual Studio .NET, а также узнаем, какие окна и инструменты она содержит.
При первом запуске Visual Studio .NET можно настроить среду разработчика в соответствии с типом задач, которые предстоит решать с ее помощью. Сведения об этом вводятся на странице My Profile (рис. 1).
Рис. 1. Диалоговая панель My Profile
Поля на этой странице имеют следующее назначение:
Стартовая страница
Если в диалоговой панели My Profile в поле At Startup указано Show Start Page, при последующих запусках Visual Studio можно увидеть экран стартовой страницы (рис. 2).
Рис. 2. Стартовая страница Visual Studio .NET
В левой части этой страницы находятся ссылки на Web-ресурсы, такие как страница с обновлениями и дополнениями к продукту (What’s New), ссылки на страницы сообществ разработчиков, новостей MSDN и поиска в MSDN нужных разделов. Там же можно открыть страницу My Profile. В правой части страницы можно выбрать один из проектов, над которым недавно велась работа, открыть произвольный проект или создать новый.
Создание нового проекта
Если в меню среды разработки выбрать пункт File / New / Project, на экране появится диалоговая панель New Project (рис. 3). Приложение в Visual Studio .NET может состоять из нескольких проектов, совокупность которых называется термином Solution (решение).
Рис. 3. Диалоговая панель New Project
В левой части этой диалоговой панели можно выбрать тип проекта. В общем случае можно выбрать проекты, созданные на языках программирования Visual Basic .NET, C#, C++, а также на ряде других. Этот список зависит от того, какие языки были выбраны при установке Visual Studio, а также от того, были ли приобретены и установлены дополнительные языки программирования сторонних производителей.
В правой части экрана можно выбрать один из предложенных шаблонов для данного типа проектов:
При создании нового проекта в поле Location необходимо указать имя каталога, в котором следует сохранить его файлы. При этом в данном каталоге автоматически будет создан другой каталог, имя которого совпадает с именем проекта. Например, при создании проекта MyProject и указании в поле Location каталога С:\Projects соответствующее решение будет создано в каталоге С:\Projects\MyProject\ MyProject.sln. По умолчанию проекты сохраняются в файле My Documents\Visual Studio Projects\Имя проекта.
Окна среды разработки Visual Studio
В данном разделе мы рассмотрим окна, имеющиеся в среде разработки (Integrated Development Environment, IDE) Visual Studio .NET. Как уже было сказано выше, вид среды разработки Visual Studio .NET зависит от того, какие настройки были указаны в окне MyProfile. На рис. 4 представлен вид среды разработки, установленный для типа разработки Visual Basic Developer.
Рис. 4. Среда разработки Visual Studio .NET
Как и большинство современных приложений, среда разработки Visual Studio .NET содержит меню и набор инструментальных панелей. В левой части среды разработки присутствует элемент управления со значком окна Server Explorer; это окно появится, если указатель мыши окажется над данным значком. Там же имеется и значок окна Toolbox — оно появится, если поместить указатель мыши над этим значком.
В правой части экрана находится окно Solution Explorer. В нем можно увидеть, из каких проектов состоит решение и какие файлы входят в состав этих проектов.
Ниже окна Solution Explorer расположено окно свойств (Properties). Это окно содержит список атрибутов объекта, выделенного в данный момент.
Давайте выясним, зачем нужны эти и другие окна среды разработки.
Окно Toolbox
В окне Toolbox (его можно отобразить на экране с помощью команды меню View / Toolbox) находится список элементов управления, которые можно использовать на формах приложения. То, какой набор компонентов доступен в данный момент, зависит от типа разрабатываемого приложения. Например, если в данный момент разрабатывается приложение типа Windows Forms, в этом окне будут присутствовать элементы управления, которые можно использовать в Windows-приложениях; если же разрабатывается Web-форма, в этом окне будут находиться инструменты для работы с элементами управления Web Controls, и т.д.
При необходимости можно изменить отображаемый в окне Toolbox набор элементов управления, добавив другие компоненты .NET или элементы ActiveX (в том числе созданные независимыми производителями). Для этой цели можно использовать команду меню Tools / Customize Toolbox и с помощью диалоговой панели Customize Toolbox (рис. 5) выбрать элементы управления ActiveX или элементы управления .NET, которые мы хотим отобразить в окне Toolbox.
Рис. 5. Диалоговая панель Customize Toolbox
Окно Solution Explorer
Как мы уже знаем, решение — это набор проектов, из которых состоит приложение. Окно Solution Explorer (которое можно отобразить на экране с помощью команды меню View / Solution Explorer) позволяет просматривать состав проектов, входящих в решение, в виде иерархической структуры, а также связи между проектами и их компонентами (рис. 6). Компонентами проектов могут быть формы, классы, модули, а также другие файлы, которые требуются для создания приложения. Если нужно отредактировать компонент проекта, следует дважды щелкнуть по его имени в окне Solution Explorer.
Рис. 6. Окно Solution Explorer
С помощью кнопок, расположенных в верхней части окна Solution Explorer, можно указать, что именно должно отражаться в среде разработки:
Окно Class View
Окно Class View (доступно с помощью команды меню View / Class View) позволяет просмотреть список свойств и методов созданных в приложении классов (рис. 7). Выбрав свойство или метод, можно щелкнуть на его имени правой клавишей мыши и выбрать одно из возможных действий с данным свойством или методом. По двойному щелчку по имени класса произойдет его загрузка в редактор кода.
Рис. 7. Окно Class View
Окно Server Explorer
Окно Server Explorer (команда меню View / Server Explorer, рис. 8), позволяет просматривать сведения о службах, выполняющихся на конкретных серверах. К таким службам, в частности, относятся службы Crystal Reports Services, журнал событий, очереди сообщений, службы серверов баз данных, таких как Microsoft SQL Server.
Рис. 8. Окно Server Explorer
Большинство этих служб представлено в окне в виде иерархического дерева, позволяющего просматривать сведения, связанные с данными службами, и иногда добавлять новые элементы. С помощью перетаскивания значка службы или ее элемента в дизайнер можно организовать ее использование в приложении. Так, при переносе значка таблицы сервера баз данных на форму разрабатываемого приложения можно создать компонент DataAdapter для извлечения данных из этой таблицы.
Окно Properties
Окно Properties (команда меню View / Properties Window) предназначено для изменения свойств элементов управления и других классов создаваемого приложения (рис. 9). Свойства можно отсортировать по алфавиту или по категориям (для этой цели в верхней части этого окна имеются соответствующие кнопки). Редактирование свойств может осуществляться путем ввода значения, выбора его из выпадающего списка либо с помощью установки его значения в отдельной диалоговой панели — это зависит от типа конкретного свойства. Таким же образом можно изменять свойства проекта, приложения и т.п.
Рис. 9. Окно Properties
Окно Object Browser
Окно Object Browser, доступное с помощью команды меню View / Other Windows / Object Browser (рис. 10), так же как и окно Class View, позволяет просмотреть список классов, их свойств и методов. Однако Object Browser позволяет просмотреть все компоненты, на которые ссылается класc, а также, при необходимости, компоненты, на которые нет ссылок в данном проекте, тогда как с помощью окна Class View можно просматривать сведения только о классах из данного проекта. С помощью Object Browser можно также просмотреть объявления свойств и методов.
Рис. 10. Окно Object Browser
Окно Task List
Окно Task List, доступное с помощью команды меню View / Other Windows / Task List (рис. 11), содержит список задач (TO DO list), ошибок компиляции и другую информацию. В этот список можно внести свое задание, щелкнув по надписи Click here to add a new task, добавив в код комментарий вида «TODO: <текст задачи>» либо выбрав из контекстного меню строки кода пункт Add a Task List Shortcut. При щелчке по тексту задачи в этом окне редактор кода откроется в месте, где находится соответствующий комментарий.
Рис. 11. Окно Task List
Режимы работы среды разработки
Cреда разработки Visual Studio .NET содержит два типа окон — окна инструментов и окна документов. Окна инструментов (часть из которых была описана выше) доступны с помощью команд меню View и некоторых других, и их доступность зависит от типа приложения и от того, какие модули расширения (дополнительные утилиты и инструменты, в том числе произведенные сторонними разработчиками) добавлены к среде разработки. В окнах же документов можно редактировать компоненты проектов.
Окна инструментов
С окнами инструментов можно производить различные манипуляции. В частности, можно заставить их автоматически появляться и исчезать, группировать их в виде многостраничного блокнота, варьировать их расположение в среде разработки, делать их «плавающими» и даже отображать на дополнительном мониторе, если использование такового поддерживается операционной системой.
Некоторые окна инструментов, например окно Web Browser, можно создавать в виде нескольких экземпляров (это можно сделать, выбрав пункт меню Windows / New Window). Можно также заставить окна инструментов автоматически исчезать, если они в данный момент не являются активными, — в этом случае на экране отображаются название и пиктограмма окна, над которой можно поместить указатель мыши, если окно нужно отобразить целиком. Если необходимо предотвратить исчезновение окна с экрана, следует щелкнуть мышью по изображению канцелярской кнопки на заголовке окна.
Режимы отображения окон инструментов
Visual Studio .NET поддерживает два режима отображения окон документов в среде разработки: многодокументный интерфейс (Multiple Document Interface, MDI) и интерфейс в виде блокнота (Tabbed Documents). Выбрать нужный режим отображения можно в разделе Environment / General диалоговой панели Options (ее можно отобразить с помощью команды меню Tools / Options).
Окна документов
Окна документов предназначены для редактирования компонентов проектов. Их взаимное расположение зависит от выбранного режима отображения окон в среде разработки.
Редактор кода
Ниже будут рассмотрены возможности, предоставляемые редактором кода Visual Studio .NET.
Как и в прежней версии Visual Studio, после набора имени объекта и ввода точки на экране появляется список свойств и методов данного объекта. При вводе имени метода можно увидеть на экране описание метода и его параметров.
Окно редактирования можно разбить на несколько частей, в которых будут отображаться разные фрагменты кода. Допустимо также отобразить второе окно редактирования с помощью пункта меню Window / New Window.
В редакторе кода можно осуществлять контекстный поиск и замену текста в текущей процедуре, текущем модуле или в выделенном фрагменте кода с помощью стандартной диалоговой панели Windows Find and Replace. В строке для поиска могут содержаться символы «*» и «?», означающие любую последовательность символов и любой символ соответственно.
Возможен также поиск и замена фрагментов текста во всех файлах проекта. В этом случае следует использовать диалоговые панели Find in Files и Replace in Files.
Помимо фрагментов кода можно искать также названия классов и структур — для этой цели используется диалоговая панель Find Symbols. Результаты поиска отображаются в окне Find Symbol Results (рис. 12).
Рис. 12. Диалоговая панель Find Symbol и окно Find Symbol Results
В редакторе кода можно установить закладку на какую-либо строку кода и вернуться к ней позже. Закладки не исчезают и при сохранении проекта.
Можно также создать комментарий, связанный с выделенным фрагментом текста, с помощью команды меню Edit / Advanced / Comment Selection.
Возможно перемещение фрагментов текста посредством мыши в другое место, копирование фрагментов, а также перемещение фрагментов текста из редактора кода в окно Toolbox (рис. 13).
Рис. 13. Окно Toolbox с фрагментами текста
Фрагменты текста в окне Toolbox сохраняются до закрытия Visual Studio и могут при необходимости быть перенесены в редактор кода.
С помощью комбинации клавиш Shift+Ctrl+ Enter можно развернуть окно редактора кода на весь экран и вернуть его в исходное состояние, а комбинации Ctrl+Tab и Shift+Ctrl+Tab позволяют перемещаться между окнами документов.
Буфер обмена
Visual Studio .NET позволяет сохранить до 20 фрагментов текста или иных элементов проектов в буфере обмена (Clipboard Ring). Удерживая клавиши Ctrl и Shift, можно просматривать по очереди элементы, хранящиеся в буфере обмена, нажимая на клавишу V и поочередно отображая эти элементы в редакторе кода. После нахождения необходимого фрагмента можно поместить его в редактор кода, отпустив клавиши Ctrl и Shift. Можно также просмотреть содержимое буфера обмена, щелкнув по закладке Clipboard Ring в окне Toolbox, выбрать нужный элемент и перетащить его в окно редактора кода.
Макросы
Среда разработки Visual Studio .NET позволяет записывать макросы подобно тому, как это делается в приложениях Microsoft Office. Записанный макрос можно сохранить либо на время текущего сеанса работы с Visual Studio, либо в отдельном проекте, который затем можно добавить к любому решению.
Работа с элементами управления
В среде Visual Studio имеется ряд инструментов для манипуляции элементами управления на этапе разработки приложений Windows Forms. Рассмотрим их подробнее.
При создании форм для ввода данных нередко требуется установить определенный порядок обхода элементов управления при нажатии клавиши Tab. Для просмотра и изменения этого порядка следует выбрать пункт меню View / Tab Order и установить порядок обхода элементов управления, выбирая их последовательно с помощью мыши (рис. 14).
Рис. 14. Установка порядка обхода элементов управления
Если установить свойство Font формы до того, как на нее будут помещены какие-либо элементы управления, все вновь помещаемые на форму элементы управления унаследуют это свойство формы. При необходимости присвоить одно и то же значение какого-либо свойства нескольким элементам управления можно выделить их (обведя их с помощью мыши или выбрав с помощью щелчков мыши при нажатой клавише Shift или Ctrl) и установить нужные значения общих свойств этих элементов с помощью окна Properties. Для выбора нескольких элементов внутри контейнера следует сначала установить на него фокус ввода.
Редактор форм Visual Studio .NET обладает различными средствами выравнивания элементов на форме (выравнивание по вертикали, горизонтали, установка одинакового размера, установка равных расстояний между элементами по вертикали или горизонтали). Все эти средства можно найти в меню Format, а для их использования следует выбрать нужные компоненты на форме и затем применить к ним одну из команд данного меню. Можно также указать, какие элементы расположены поверх других.
Если выбрать пункт меню Format / Lock Controls, все элементы управления на данной форме будут заблокированы. Блокировка элементов управления применяется тогда, когда пользовательский интерфейс приложения уже спроектирован и нужно избежать случайного смещения элементов управления при щелчках на них с целью добавления связанного с ними кода.
Итак, мы видим, что среда разработки Visual Studio .NET стала гораздо более удобной, нежели среда разработки Visual Studio 6, — в ней появилось много новых инструментов, средств конфигурации и средств, упрощающих проектирование приложений.
В следующей части данной статьи мы продолжим знакомство с Visual Studio .NET и рассмотрим создание Windows-приложений с помощью этого средства разработки.
No 'Tools' Option for Visual Studio Code \\The menu bar is missing it
Across the top I see: [File Edit Selection View Go Debug Terminal Help] No Tools options. And some of the things I was trying to do, like reset to default settings, I can only do through that option. Here is the info about my version (yes i have checked for updates)
2 Answers 2
If some other noob like me shows up looking for a «Tool» dropdown menu you should stop looking : it does not exist in Visual Studio Code but it does in Visual Studio . not the same software, almost same name.
Где Visual Studio ищет заголовочные файлы C ++?
Я проверил копию приложения С++ из SourceForge (HoboCopy, если вам интересно) и попытался скомпилировать его.
Visual Studio сообщает мне, что он не может найти конкретный файл заголовка. Я нашел файл в исходном дереве, но где его нужно поместить, чтобы он был найден при компиляции?
Существуют ли специальные каталоги?
6 ответов
Visual Studio ищет заголовки в следующем порядке:
- В текущем исходном каталоге.
- В дополнительных каталогах Включить в свойствах проекта (в C++ | Общие).
- В Visual Studio C++ Включите каталоги в разделе Инструменты → Параметры → Проекты и решения → V C++ Каталоги.
- В новых версиях Visual Studio (2015+) вышеуказанная опция устарела, и список включаемых по умолчанию каталогов доступен в Свойства проекта → Конфигурация → V C++ Каталоги
В вашем случае добавьте каталог с заголовком в свойства проекта (Свойства проекта → Конфигурация → C/C++ → Общие → Дополнительные каталоги включения).
Если проект поставляется с файлом проекта Visual Studio, то он уже должен быть настроен для поиска заголовков для вас. Если нет, вам нужно будет добавить каталог файлов include к настройкам проекта, щелкнув правой кнопкой мыши проект и выбрав «Свойства», нажав «C/С++» и добавив каталог, содержащий включенные файлы, в «Дополнительные каталоги включения»,.
Попробовал добавить это как комментарий к Rob Prouse, но отсутствие форматирования сделало его непонятным.
В Visual Studio 2010 диалоговое окно «Инструменты | Параметры | Проекты и решения | VС++-каталоги» сообщает, что «Редактирование каталогов VС++ в» Инструменты » > » Параметры «устарело», предлагая использовать довольно интуитивно понятный Property Manager.
Если вы действительно хотите обновить значение по умолчанию (IncludePath), вам нужно взломать соответствующую запись в одном из файлов XML:
\ Program Files (X86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\Win32\PlatformToolsets\V100\Microsoft.Cpp.Win32.v100.props
\ Program Files (X86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\PlatformToolsets\v100\Microsoft.Cpp.X64.v100.props
(Возможно, не рекомендуется Microsoft).
На самом деле в моем windows 10 с сообществом visual studio 2017 путь заголовков C++:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include
C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt
Первый содержит стандартные заголовки C++, такие как <iostream> , <algorithm> . Второй содержит старые заголовки C, такие как <stdio.h> , <string.h> . Номер версии может отличаться в зависимости от вашего программного обеспечения.
Надеюсь, это поможет.
Кажется, что ошибка в сообществе Visual Studio 2015. Для 64-битного проекта папка include не найдена, если только она не находится в списке дополнительных пакетов Include Folders в win32.
Configure VS Code for Microsoft C++
In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger 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 details about the Microsoft C++ toolset 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:
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 ) ).
Install the Microsoft Visual C++ (MSVC) compiler toolset.
If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it’s not installed, then check the box and select the Modify button in the installer.
You can also install the Desktop development with C++ workload without a full Visual Studio IDE installation. From the Visual Studio Downloads page, scroll down until you see Tools for Visual Studio 2022 under the All Downloads section and select the download for Build Tools for Visual Studio 2022.
This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check the Desktop development with C++ workload and select Install.
Note: You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to compile, build, and verify any C++ codebase as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise) that you are actively using to develop that C++ codebase.
Check your Microsoft Visual C++ installation
To use MSVC from a command line or VS Code, you must run from a Developer Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.
To open the Developer Command Prompt for VS, start typing ‘developer’ in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Select the item to open the prompt.
You can test that you have the C++ compiler, cl.exe , installed correctly by typing ‘cl’ and you should see a copyright message with the version and basic usage description.
If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn’t want to put projects there), navigate to your user folder ( C:\users\
Note: If for some reason you can’t run VS Code from a Developer Command Prompt, you can find a workaround for building C++ projects with VS Code in Run VS Code outside a Developer Command Prompt.
Create Hello World
From the Developer Command Prompt, create an empty folder called "projects" where you can store all your VS Code projects, then create a subfolder called "helloworld", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:
The "code ." command opens VS Code in the current working folder, which becomes your "workspace". 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.
Run helloworld.cpp
Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.
Open helloworld.cpp so that it is the active file.
Press the play button in the top right corner of the editor.
Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system.
You’ll only be asked to choose a compiler the first time you run helloworld.cpp . This compiler will be set as the "default" compiler in tasks.json file.
After the build succeeds, your program’s output will appear in the integrated Terminal.
If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.
The first time you run your program, the C++ extension creates tasks.json , which you’ll find in your project’s .vscode folder. tasks.json stores build configurations.
Your new tasks.json file should look similar to the JSON below:
Note: You can learn more about tasks.json variables in the variables reference.
The command setting specifies the program to run; in this case that is "cl.exe". The args array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler.
This task tells the C++ compiler to take the active file ( $
The label value is what you will see in the tasks list; you can name this whatever you like.
The detail value is what you will as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.
The problemMatcher value selects the output parser to use for finding errors and warnings in the compiler output. For cl.exe, you’ll get the best results if you use the $msCompile problem matcher.
From now on, the play button will read from tasks.json to figure out how to build and run your program. You can define multiple build tasks in tasks.json , and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler, you can run Tasks: Configure default build task. Alternatively you can modify the tasks.json file and remove the default by replacing this segment:
Modifying tasks.json
You can modify your tasks.json to build multiple C++ files by using an argument like "$
Debug helloworld.cpp
- Go back to helloworld.cpp so that it is the active file.
- Set a breakpoint by clicking on the editor margin or using F9 on the current line.
- From the drop-down next to the play button, select Debug C/C++ File.
- Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system (you’ll only be asked to choose a compiler the first time you run/debug helloworld.cpp ).
The play button has two modes: Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can just click the play button to debug, instead of selecting the drop-down menu item.
If you get an error trying to build and debug with cl.exe, make sure you have started VS Code from the Developer Command Prompt for Visual Studio using the code . shortcut.
Explore the debugger
Before you start stepping through the 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 line where you set a breakpoint before starting the debugger:
The Run and Debug 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.
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, select 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.
Customize debugging with launch.json
When you debug with the play button or F5 , the C++ extension creates a dynamic debug configuration on the fly.
There are cases where you’d want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json file.
To create launch.json , choose Add Debug Configuration from the play button drop-down menu.
You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: cl.exe build and debug active file.
VS Code creates a launch.json file, which looks something like this:
In the JSON above, program specifies the program you want to debug. Here it is set to the active file folder ( $
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.
From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.
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.
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 compilerPath setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful 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++ compilerOpe
- Then look for g++ on Windows Subsystem for Linux (WSL)
- Then g++ for Mingw-w64.
If you have g++ or WSL installed, you might need to change compilerPath to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: "C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe".
Reusing your C++ configuration
VS Code is now configured to use the Microsoft C++ compiler. The configuration applies to the current workspace. To reuse the configuration, just copy the JSON files to a .vscode folder in a new project folder (workspace) and change the names of the source file(s) and executable as needed.
Run VS Code outside the Developer Command Prompt
In certain circumstances, it isn’t possible to run VS Code from Developer Command Prompt for Visual Studio (for example, in Remote Development through SSH scenarios). In that case, you can automate initialization of Developer Command Prompt for Visual Studio during the build using the following tasks.json configuration:
Note: The path to VsDevCmd.bat might be different depending on the Visual Studio version or installation path. You can find the path to VsDevCmd.bat by opening a Command Prompt and running dir "\VsDevCmd*" /s .
Troubleshooting
The term ‘cl.exe’ is not recognized
If you see the error "The term ‘cl.exe’ is not recognized as the name of a cmdlet, function, script file, or operable program.", this usually means you are running VS Code outside of a Developer Command Prompt for Visual Studio and VS Code doesn’t know the path to the cl.exe compiler.
VS Code must either be started from the Developer Command Prompt for Visual Studio, or the task must be configured to run outside a Developer Command Prompt.