CPP Overview MSVC 170
CPP Overview MSVC 170
7 Note
If you're looking for a Microsoft Visual C++ Redistributable package so that you
can run a program, see the latest supported Visual C++ downloads.
Microsoft Visual C++ (MSVC) refers to the C++, C, and assembly language development
tools and libraries available as part of Visual Studio on Windows. These tools and
libraries let you create native Windows desktop and server applications, Universal
Windows Platform (UWP) apps, or managed apps and libraries that use the .NET
Framework. Create cross-platform libraries and apps that run on Windows, Linux,
Android, and iOS. You can use MSVC to write anything from simple console apps to the
most sophisticated and complex apps for Windows desktop. Write device drivers and
operating system components or cross-platform games for mobile devices. Target
anything from the smallest IoT devices to multi-server high performance computing in
the Azure cloud.
Visual Studio 2015, 2017, 2019, and 2022 can be installed side-by-side. You can use
Visual Studio 2019 (compiler toolset v142) or Visual Studio 2017 (v141) to edit and build
programs using the toolset from Visual Studio 2017 (v141) and Visual Studio 2015
(v140).
Supported platforms
Find out which platforms the Microsoft C/C++ compiler supports.
Standard C++
Learn about C++, get an overview of Modern C++, and find links to books, articles,
talks, and events
Learn Visual Studio and make your first C++ project
Start learning how to write C++ in Visual Studio.
Parallel programming
Learn how to use the Parallel Patterns Library, C++ AMP, OpenMP, and other features
that are related to multithreading on Windows.
Data access
Connect to databases using ODBC and OLE DB.
C language reference
The reference guide to the Microsoft implementation of the C programming language.
Feedback
Was this page helpful? Yes No
As part of the Visual Studio Integrated Development Environment (IDE), Microsoft C++
(MSVC) shares many windows and tools in common with other languages. Many of
those, including Solution Explorer, the code editor, and the debugger, are documented
under Visual Studio IDE. Often, a shared tool or window has a slightly different set of
features for C++ than for other languages. A few windows or tools are only available in
Visual Studio Professional or Visual Studio Enterprise editions.
In addition to shared tools in the Visual Studio IDE, MSVC has several tools specifically
for native code development. These tools are also listed in this article. For a list of which
tools are available in each edition of Visual Studio, see C++ Tools and Features in Visual
Studio Editions.
Create projects
A project is basically a set of source code files and resources such as images or data files
that are built into an executable program or library.
Visual Studio provides support for any project system or custom build tools that you
wish to use, with full support for IntelliSense, browsing and debugging:
MSBuild is the native project system for Visual Studio. When you select File > New
> Project from the main menu, you see many kinds of MSBuild project templates
that get you started quickly developing different kinds of C++ applications.
In general, you should use these templates for new projects unless you are using
existing CMake projects, or you are using another project system. For more
information, see Creating and managing MSBuild-based projects.
CMake is a cross-platform build system that is integrated into the Visual Studio IDE
when you install the Desktop development with C++ workload. You can use the
CMake project template for new projects, or simply open a folder with a
CMakeLists.txt file. For more information, see CMake projects in Visual Studio.
Any other C++ build system, including a loose collection of files, is supported via
the Open Folder feature. You create simple JSON files to invoke your build
program and configure debugging sessions. For more information, see Open
Folder projects for C++.
Obtain libraries
Use the vcpkg package manager to obtain and install third-party libraries. Over 1700
open-source library packages are currently available in the catalog.
Write code
After you create a project, all the project files are displayed in the Solution Explorer
window. (A solution is a logical container for one or more related projects.) When you
click on a .h or .cpp file in Solution Explorer, the file opens up in the code editor.
The code editor is a specialized word processor for C++ source code. It color-codes
language keywords, method and variable names, and other elements of your code to
make the code more readable and easier to understand. It also provides tools for
refactoring code, navigating between different files, and understanding how the code is
structured. For more information, see Writing and refactoring code.
You can also use the compiler (cl.exe) and many other build-related standalone tools
such as NMAKE and LIB directly from the command line. For more information, see Build
C/C++ code on the command line and C/C++ Building Reference.
Debug
You can start debugging by pressing F5. Execution pauses on any breakpoints you have
set (by pressing F9). You can also step through code one line at a time (F10), view the
values of variables or registers, and even in some cases make changes in code and
continue debugging without re-compiling. The following illustration shows a debugging
session in which execution is stopped on a breakpoint. The values of the data structure
members are visible in the Watch Window.
For more information, see Debugging in Visual Studio.
Test
Visual Studio includes the Microsoft Unit Test Framework for C++, as well as support for
Boost.Test, Google Test, and CTest. Run your tests from the Test Explorer window:
For more information, see Verifying Code by Using Unit Tests and Write unit tests for
C/C++ in Visual Studio.
Analyze
Visual Studio includes static code analysis tools that can detect potential problems in
your source code. These tools include an implementation of the C++ Core Guidelines
rules checkers. For more information, see Code analysis for C/C++ overview.
You can also deploy a native C++ desktop to another computer. For more information,
see Deploying Desktop Applications.
For more information about deploying a C++/CLI program, see Deployment Guide for
Developers,
Next steps
Explore Visual Studio further by following along with one of these introductory articles:
Feedback
Was this page helpful? Yes No
Visual Studio 2022 brings many updates and fixes to the Microsoft C++ compiler and
tools. The Visual Studio IDE also offers significant improvements in performance and
productivity, and now runs natively as a 64-bit application.
For more information on what's new in all of Visual Studio, see What's new in
Visual Studio 2022.
For information about what's new in the C++ docs, see Microsoft C++ docs:
What's new.
For information about version build dates, see Visual Studio 2022 Release History.
ノ Expand table
What's new for C++ developers What's New for C++ Developers in
Visual Studio 2022 17.11
Standard Library (STL) merged C++26 and C++23 STL Changelog 17.11
features, C++20 defect reports, LWG issue resolutions,
performance improvements, enhanced behavior, and fixed
bugs
New features in the Visual Studio 17.11 IDE Visual Studio 2022 version 17.11
Release Notes
CMake debugging
You can now debug your CMake scripts and CMakeLists.txt files in the Visual
Studio debugger for CMake projects that target Linux via Windows Subsystem
for Linux (WSL) or SSH. To start a CMake debugging session in Visual Studio, set
a breakpoint in your CMakeLists.txt file and then navigate to Project >
Configure Cache with CMake Debugging.
Copilot
When you hover over symbols in the code editor, click the Copilot Tell me more
button in the Quick Info dialog to learn more about a given symbol:
GitHub Copilot can generate naming suggestions for your identifiers (variables,
methods, or classes) based on how your identifier is used and the style of your
code.
You need an active GitHub Copilot subscription . Right-click the variable you wish
to rename, and choose Rename ( Ctrl+R , Ctrl+R ). Select the GitHub Copilot
sparkle icon to generate naming suggestions.
Debugging
Conditional breakpoints in C++ are significantly faster.
Diagnostics improvements
Improved diagnostics when calling std::get<T> on a std::tuple that has
multiple instances of T in its template arguments. MSVC used to report:
error C2338: static_assert failed: 'duplicate type T in get<T>(tuple)' .
Now it reports:
error C2338: static_assert failed: 'get<T>(tuple<Types...>&) requires T to
Now it reports:
error C2338: static_assert failed: 'ranges::to requires the result to be
ノ Expand table
What's new for C++ developers What's new for C++ Developers in
Visual Studio 2022 17.10
Standard Library (STL) merged C++26 and C++23 STL Changelog 17.10
features, C++20 defect reports, LWG issue resolutions,
performance improvements, enhanced behavior, and fixed
bugs
New features in the Visual Studio 17.10 IDE Visual Studio 2022 version 17.10
Release Notes
MSVC Toolset Update: The MSVC toolset version is updated from 19.39 to 19.40.
This may affect projects that have version assumptions. For more information
about some ways in which this will affect projects that assume that MSVC versions
are all 19.3X for Visual Studio 2022 releases, see MSVC Toolset Minor Version
Number 14.40 in VS 2022 v17.10 .
Standard Library Enhancements: The standard library added support for P2510R3
Formatting Pointers , which brings the set of format specifiers for pointers when
using std::format more in line with those that already exist for integers. Improved
the vectorized implementations of std::min_element , std::ranges::min , and
friends.
Build Insights: Now provides template instantiation information. See Templates
View for Build Insights in Visual Studio or the Pure Virtual C++ - Templates view
for Build Insights in Visual Studio recording.
Unreal Engine Plugin: There's a new opt-in feature for the Unreal Engine Plugin to
run in the background, reducing startup costs. This is an opt-in feature that is
activated via Tools > Options > Unreal Engine.
New features for Linux: See New Linux Development Features in Visual Studio .
CMake Targets: You can now pin targets in the CMake Targets View.
Connection Manager UX: The user experience provides a more seamless
experience when connecting to remote systems. For more information, see
Usability Improvements in the Visual Studio Connection Manager .
Pull request comments: You can now view GitHub and Azure DevOps comments
directly in your working file. Enable the feature flag, Pull Request Comments in
Options > Environment > Preview Features and checkout the pull request branch
to get started.
AI-Generated Content: GitHub Copilot can now draft pull request descriptions.
Requires an active GitHub Copilot subscription. Try it out by clicking the Add AI
Generated Pull Request Description sparkle pen icon within the Create a Pull
Request window.
Image Preview: Hover over an image path to see a preview with size details. The
size is capped to 500 px wide and high.
The GitHub Copilot interface is in the top-right corner of Visual Studio. To use it,
you need an active GitHub Copilot subscription.
ノ Expand table
What's new for C++ developers What's new for C++ Developers in
Visual Studio 2022 17.9
New features in the Visual Studio 17.9 IDE Visual Studio 2022 version 17.9 Release
Notes
For more information about See
reference link to navigate to where your code uses something from that header
file. To view the build time of your #include directives, run Build Insights by
navigating to Build > Run Build Insights on Solution > Build.
Memory layout visualization, which shows how memory is arranged for your
classes, structs, and unions. Hover over a type and choose the Memory Layout link
in the Quick Info to open a dedicated window displaying the memory layout of the
selected type. Hovering over individual data types within this window provides
detailed information about their size and offset within the type.
You can now specify your own custom CMake executable. This feature is useful if
you want to use a specific version of CMake that isn't shipped with Visual Studio.
Navigate to Tools > Options and select CMake > General. Select Enable custom
CMake executable and specify the directory path of your CMake executable.
Improved IntelliSense for Unreal Engine projects.
Improved C++23 support: std::format and std::span formattable , range_format ,
format_kind , and set_debug_format() as part of P2286R8 Formatting Ranges
<mdspan> per P0009R18 and subsequent wording changes that were applied to
the C++23 Standard. Also, format() can format pointers per P2510R3 .
ノ Expand table
What's new for C++ developers What's new for C++ Developers in
Visual Studio 2022 17.8
Standard Library (STL) merged C++26, C++23 features, STL Changelog 17.8
C++20 extensions, LWG issue resolutions, performance
improvements, enhanced behavior, and fixed bugs
New features in the Visual Studio 17.8 IDE Visual Studio 2022 version 17.8
Release Notes
C++ structured diagnostics in the Output window and a new problem details
window that provides more information about the error. For more information, see
Structured SARIF Output and Problem Details Window.
A feature that lets you visualize the size and alignment of your classes, structs,
unions, base types, or enums even before the code is compiled. Hover over the
identifier and a Quick Info displays the size and alignment information.
A feature that suggests when to mark member functions const because they don’t
modify the object’s state. Hover over a member function and click the light bulb
icon to mark the function as const .
Visual Studio now prompts you to mark global functions as static via a screwdriver
icon that appears by the function name. Click the screwdriver icon to mark the
function as static.
Unused #include directives are dimmed in the editor. You can hover over a
dimmed include and use the light bulb menu to either remove that include or all
unused includes. You can also add #include directives for entities that are
indirectly included via other headers. For more information, see Clean up C/C++
includes in Visual Studio.
More Unreal Engine support:
Unreal Engine Test Adapter lets you discover, run, manage, and debug your
Unreal Engine tests without leaving the Visual Studio IDE.
With Unreal Engine Code Snippets, you can find common Unreal Engine
constructs as snippets in your member list.
Build Insights is now integrated with Visual Studio 2022 and works with MSBuild
and CMake projects using MSVC. You can now see additional information about
the compilation of a function such as how long it took to compile and the
number of ForceInlines, and the impact of header files on build time. For more
information, see Tutorial: Troubleshoot function inlining on build time and
Tutorial: Troubleshoot header file impact on build time.
Remote Linux unit test support now lets you run your CTest and GTest tests on
your remote Linux machines from Visual Studio’s Test Explorer, just like your local
tests.
What's new for C++ in Visual Studio version
17.7
Released Aug 2023
ノ Expand table
What's new for C++ developers What’s new for C++ Developers in
Visual Studio 2022 17.7
New C++ features specific to game development Unleashing the Power of Visual Studio
2022 for C++ Game Development
Standard Library (STL) merged C++23 features, LWG STL Changelog 17.7
issue resolutions, performance improvements,
enhanced behavior, and fixed bugs
New features in the Visual Studio 17.7 IDE Visual Studio 2022 version 17.7 Release
Notes
ノ Expand table
For more information about See
What's new for C++ developers What’s New for C++ Developers in
Visual Studio 2022 17.6
Standard Library (STL) merged C++23 features, LWG STL Changelog 17.6
issue resolutions, performance improvements,
enhanced behavior, and fixed bugs
New features in the Visual Studio 17.6 IDE Visual Studio 2022 version 17.6 Release
Notes
ノ Expand table
Standard Library (STL) merged C++23 features, LWG issue STL Changelog 17.5
resolutions, performance improvements, enhanced behavior,
and fixed bugs
New features in the Visual Studio 17.5 IDE Visual Studio 2022 version 17.5
Release Notes
don't produce function calls in generated code, even in debug mode. This change
avoids named casts causing unnecessary overhead in debug builds. /permissive-
(or an option that implies it, such as /std:c++20 or std:c++latest ) is required.
Added support for Linux Console in the Integrated Terminal, which allows for
terminal I/O.
Added initial experimental support for C11 atomic primitives ( <stdatomic.h> ). You
can enable this experimental feature with the /experimental:c11atomics option in
/std:c11 mode or later.
A new preview feature, Remote File Explorer, lets you view the file directory on
your remote machines within VS, and upload and download files to it.
Go To Definition for C++ now uses a more subtle indicator of the operation taking
more time, replacing the modal dialog from previous versions.
We now ship a native Arm64 Clang toolset with our LLVM workload, allowing
native compilation on Arm64 machines.
Added support for opening a Terminal window into the currently running
Developer Container.
You can now view properties from base classes modified in an Unreal Blueprint
asset without leaving Visual Studio. Double-click in a Blueprint reference for a C++
class or property to open the UE Asset Inspector in Visual Studio.
Enabled Test Explorer to build and test multiple CMake targets in parallel.
ノ Expand table
What's new for C++ developers What’s New for C++ Developers in
Visual Studio 2022 17.4
Standard Library (STL) merged C++23 features, LWG STL Changelog 17.4
issue resolutions, performance improvements,
enhanced behavior, and fixed bugs
New features in the Visual Studio 17.4 IDE Visual Studio 2022 version 17.4 Release
Notes
For more information about See
Improved compiler error messages to provide more correct and useful information,
especially for concepts.
Added support for C23 attributes to IntelliSense and continued progress in C++20
modules support.
Upgraded the version of LLVM shipped with Visual Studio to 15.0.1. For more
information on what is available, see the LLVM and Clang release notes.
Added support to Visual Studio for vcpkg artifacts with CMake projects. For
projects that include a vcpkg manifest, the environment is activated automatically
on project open. Learn more about this feature in the vcpkg environment
activation in Visual Studio blog post.
You can now use Dev Containers for your C++ projects. Learn more about this
feature in our Dev Containers for C++ blog post.
IntelliSense now respects the order of preincluded headers when one of them is a
PCH. Previously, when a PCH was used via /Yu and force-included via /FI ,
IntelliSense would always process it first, before any other headers included via
/FI . This behavior didn't match the build behavior. With this change, /FI headers
(The compiler part isn't implemented yet. The library part was implemented in
C++20 mode when Ranges support was initially implemented.)
P0881R7 <stacktrace>
P2441R2 views::join_with
Arm64 builds of Visual Studio now bundle Arm64 versions of CMake and Ninja.
Added support for CMake Presets version 4. For details of what is available, see the
CMake release notes .
Remote system connections using the Connection Manager now support SSH
ProxyJump. ProxyJump is used to access an SSH host via another SSH host (for
example, to access a host behind a firewall).
ノ Expand table
Standard Library (STL) merged C++23 features, LWG STL Changelog 17.3
issue resolutions, performance improvements,
enhanced behavior, and fixed bugs
New features in the Visual Studio 17.3 IDE Visual Studio 2022 version 17.3 Release
Notes
ノ Expand table
What's new for C++ developers Visual Studio 2022 17.2 is now
available
For more information about See
Standard Library (STL) merged C++20 defect reports, STL Changelog 17.2
C++23 features, LWG issue resolutions, performance
improvements, enhanced behavior, and fixed bugs
New features in the Visual Studio 17.2 IDE Visual Studio 2022 version 17.2
Release Notes
Added compiler support for C++23 feature deducing this , available under the
/std:c++latest option.
Added IntelliSense support for C++23 features deducing this and if consteval .
Added inline parameter name and type hint support, toggled by pressing Alt+F1
or double-tapping Ctrl. This behavior can be customized under Tools > Options >
Text Editors > C/C++ > IntelliSense.
Added experimental support for C++20 modules in CMake projects. This support
is currently only available with the Visual Studio (MSBuild) generator.
In 17.1, we introduced peripheral register and RTOS views for embedded
developers. We continue to improve the capabilities of those views with usability
improvements in 17.2:
The RTOS tool window is now hidden by default. It prevents showing a tool
window with error messages that aren't relevant when you're not using an
RTOS.
When you double-click an RTOS object in the tool window, it adds a watch for
the object.
When you select the start and end values for the stack pointer in the RTOS tool
window, it opens in the memory window.
Added thread awareness for device targets to the call stack window.
Users can now select a pin icon next to peripherals, registers, or fields to pin
them the top of the Peripheral View.
Added implementations of the remaining C++20 defect reports (also known as
backports). All C++20 features are now available under the /std:c++20 option. For
more information about the implemented backports, see the C++20 Defect
Reports project in the Microsoft/STL GitHub repository and the MSVC's STL
Completes /std:c++20 blog post.
We added various C++23 Library features, available under the /std:c++latest
option. For more information about the new features, see the STL Repo
changelog .
Improved performance of the initial C++ indexing by up to 20%, depending on the
depth of the include graph.
ノ Expand table
What's new for C++ developers Visual Studio 2022 17.1 is now
available!
Standard Library (STL) merged C++23 features, LWG STL Changelog 17.1
issue resolutions, performance improvements,
enhanced behavior, and fixed bugs
New features in the Visual Studio 17.1 IDE Visual Studio 2022 version 17.1 Release
Notes
A new Configure Preset template is added to configure and build CMake projects
on a remote macOS system with CMakePresets.json . You can also launch CMake
targets on a remote macOS system, and then debug remotely in the Visual Studio
debugger backed by GDB or LLDB.
You can now debug core dumps on a remote macOS system from Visual Studio
with LLDB or GDB.
The versions of Clang and LLVM shipped with Visual Studio are upgraded to
v13.
Visual Studio's CMake integration is only active when a CMakeLists.txt is
identified at the root of the open workspace. If a CMakeLists.txt is identified at
another level of the workspace, then you're prompted to activate Visual Studio's
CMake integration with a notification.
New views that enable you to inspect and interact with peripheral registers on
microcontrollers and real time operating systems (RTOS) objects, available through
Debug > Windows > Embedded Registers
Added a new thread view for RTOS projects, available through Debug > Windows
> RTOS Objects. For more information, see Embedded Software Development in
Visual Studio .
ノ Expand table
New features in the Visual Studio 17.0 IDE Visual Studio 2022 version 17.0
Release Notes
Standard Library (STL) merged C++26 and C++23 STL Changelog 17.0
features, C++20 defect reports, LWG issue resolutions,
performance improvements, enhanced behavior, and fixed
bugs
An overview of some of the new features in Visual Studio 2022 version 17.0:
In Visual Studio 2022, when you start your app in the debugger, you can use the Hot
Reload button to modify your application while it's still running. This experience is
powered by native Edit and Continue. For more information about supported edits, see
Edit and Continue (C++).
WSL2 support
You can now build and debug natively on WSL2 without establishing an SSH
connection. Both cross-platform CMake projects and MSBuild-based Linux projects
are supported.
You can now configure and build your CMake projects with CMake 3.21 and
CMakePresets.json v3.
CMake project.
The Project menu in CMake projects is streamlined and exposes options to "Delete
Cache and Reconfigure" and "View Cache."
Added debugging visualizers to improve how the following types are displayed:
source_location , bind_front() , u8string (and its iterators), default_sentinel_t ,
unreachable_sentinel_t , ranges::empty_view , ranges::single_view ,
ranges::iota_view (and its iterator/sentinel), ranges::ref_view , thread ,
P1048R1 Added is_scoped_enum , a new trait for the C++ Standard library, which
detects whether a type is a scoped enumeration.
P1132R7 out_ptr() , inout_ptr()
effect.
basic_string or a vector , and makes a faster call to insert() at the end() of the
container.
We improved the performance of std::find() and std::count() for vector<bool>
19x and 26x (times, not percent).
We improved the performance of std::count() for vector<bool>
std::byte now has the same performance as unsigned char in reverse() and
variant::swap()
You can now debug processes running on a remote system from Visual Studio by
using LLDB.
Deprecation links.
IntelliSense improvements
We made improvements in C++ IntelliSense when providing navigation and syntax
highlighting for types from imported Modules and Header Units. IntelliSense is an
active area of investment for us. Help us improve: Share your feedback on
Developer Community by using Help > Send Feedback.
We improved C++ IntelliSense performance by optimizing cached header usage
and symbol database access, providing improved load times to get into your code.
The IntelliSense Code Linter for C++ is now on by default, providing instant as-
you-type suggestions and fix suggestions for common code defects.
C++ IntelliSense for CMake projects now works when using a preset with a display
name.
For information on what's new for C++ in Visual Studio 2019, see What's new for
C++ in Visual Studio 2019.
For information on what's new for C++ in Visual Studio 2017, see What's new for
C++ in Visual Studio 2017.
For information on what's new in earlier versions, see Visual C++ What's new 2003
through 2015.
Known issues
C++ IntelliSense
When importing a C++20 module or header unit, IntelliSense may stop working or
'There are too many errors' error is shown .
For more information on other open issues and available workarounds for C++ in Visual
Studio 2022, see the C++ Developer Community issues list .
Blogs
Take advantage of the insights and recommendations available in the Microsoft
Developer Blogs site to stay up to date on all new releases. The blogs include deep
dive posts on a broad range of features. The C++ Team Blog and the Visual Studio
Blog are of particular interest.
) Note: The author created this article with assistance from AI. Learn more
Feedback
Was this page helpful? Yes No
Visual Studio 2019 brings many updates and fixes to the Microsoft C++ environment.
We've fixed many bugs and issues in the compiler and tools. Many of these issues were
submitted by customers through the Report a Problem and Provide a Suggestion
options under Send Feedback. Thank you for reporting bugs!
For more information on what's new in all of Visual Studio, visit What's new in Visual
Studio 2019. For information on what's new for C++ in Visual Studio 2017, see What's
new for C++ in Visual Studio 2017. For information on what's new for C++ in Visual
Studio 2015 and earlier versions, see Visual C++ What's New 2003 through 2015. For
more information, see Microsoft C++ docs: What's new.
The compiler now supports the /std:c++20 compiler mode. Previously, C++20
features were available only in /std:c++latest mode in Visual Studio 2019. Features
that originally required /std:c++latest mode now work in /std:c++20 mode or
later in the latest versions of Visual Studio.
LLVM tools shipped with Visual Studio have been upgraded to LLVM 12. For
details, see the LLVM release notes .
All C++20 features are now available under /std:c++latest. While MSVC's
implementation of the C++20 standards (as currently published by ISO) is feature
complete, some key C++20 library features are expected to be amended by
upcoming Defect Reports (ISO C++20 bug fixes) that may change them in an ABI-
incompatible way. Please see Microsoft/STL Issue #1814 for more details.
C++20 immediate functions & constinit support added in 16.10
The final pieces of <chrono> : new clocks, leap seconds, time zones, and parsing
Implementation of <format> for text formatting
You're now required to accept or deny the host key fingerprint presented by the
server when adding a new remote connection in Visual Studio.
Added an /external switch to MSVC for specifying headers which should be treated
as external for warning purposes.
Address Sanitizer:
Our address sanitizer support on Windows is out of experimental mode and has
reached general availability.
memory pools.
Added support for the legacy GlobalAlloc and LocalAlloc family of memory
functions. You can enable these interceptors by setting the environment flag
ASAN_OPTIONS=windows_hook_legacy_allocators=true .
The IDE integration can now handle the complete collection of exceptions which
ASan can report.
The compiler and linker will suggest emitting debug information if they detect
you're building with ASan but not emitting debug information.
You can now target the LLVM version of the OpenMP runtime with the new CL
switch /openmp:llvm . This adds support for the lastprivate clause on #pragma omp
sections and unsigned index variables in parallel for loops. The /openmp:llvm
switch is currently only available for the amd64 target and is still experimental.
Visual Studio CMake projects now have first-class support for remote Windows
development. This includes configuring a CMake project to target Windows
ARM64, deploying the project to a remote Windows machine, and debugging the
project on a remote Windows machine from Visual Studio.
The version of Ninja shipped with Visual Studio on Windows has been updated to
version 1.10. For more information on what's included, see the Ninja 1.10 release
notes .
The version of CMake shipped with Visual Studio has been updated to version
3.19. For more information on what's included, see the CMake 3.19 release
notes .
IntelliSense:
MSVC now determines the correct address sanitizer runtimes required for your
binaries. Your Visual Studio project will automatically get the new changes. When
using address sanitizer on the command line, you now only need to pass
/fsanitize=address to the compiler.
Visual Studio's Connection Manager now supports private keys using the ECDSA
public key algorithm.
Updated the versions of LLVM and Clang shipped in our installer to v11. Read the
release notes for LLVM and Clang for more information.
Visual Studio will now use CMake variables from toolchain files to configure
IntelliSense. This will provide a better experience for embedded and Android
development.
C++20 Coroutines are now supported under /std:c++latest (or /std:c++20 starting
in Visual Studio 2019 version 16.11) and the <coroutine> header.
IntelliSense now provides support for C++20 <concepts> and <ranges> headers,
and rename and browsing for concept definitions.
Our STL now has support for the majority of C++20 Ranges.
C11 and C17 are now supported under the /std:c11 and /std:c17 switches.
Additional STL improvements include full support for std::atomic_ref ,
std::midpoint and std::lerp and std::execution::unseq , optimizations for
std::reverse_copy, and more.
Our code analysis tools now support the SARIF 2.1 standard: the industry standard
static analysis log format.
Missing build tools in Linux projects will now issue a warning in the toolbar and a
clear description of the missing tools in the error list.
You can now debug Linux core dumps on a remote Linux system or WSL directly
from Visual Studio.
Our remote C++ support now supports a wider range of Linux distros and shells,
including sh, csh, bash, tsch, ksh, zsh, and dash. You can override the choice of a
shell for a remote connection by modifying the new "shell" property via
ConnectionManager.exe. This support has been tested with both MSBuild-based
Linux projects and CMake projects targeting a remote Linux system or WSL.
You can now use Ninja (a build system that evaluates incremental builds very
quickly) to improve incremental build times for MSBuild-based Linux projects. You
can opt into this feature by setting "Enable Incremental Build" to "With Ninja" in
the General Property Page. Ninja (ninja-build) must be installed on your remote
Linux system or WSL.
New C++20 Standard Library features have been implemented. Please refer to
the STL Changelog on GitHub for a detailed list.
You can now edit and set default remote SSH connections in the Connection
Manager. This means you can edit an existing remote connection (for example, if
its IP address changed) and set default connections to be consumed in
CMakeSettings.json and launch.vs.json. Remote SSH connections allow you to
build and debug C++ projects on a remote Linux system directly from Visual
Studio.
You can now try out underlining code errors and see more suggested quick fixes in
C++ projects. Enable this feature under Tools > Options > Text Editor > C/C++
> Experimental. Set Disable Experimental Code Linter to false. Learn more on the
C++ Team Blog .
We've added four new code analysis rules to incorporate additional safety features
into C++: C26817, C26818, C26819, and C26820.
We've added first-class support for debugging CMake projects on remote systems
with gdbserver.
IntelliSense now has basic support for Concepts, designated initializers, and several
other C++20 features.
.ixx and .cppm files are now recognized as C++ and get treated as such by the
Ninja support for CMake for Linux/WSL: Use Ninja as the underlying generator
when building CMake projects on WSL or a remote system. Ninja is now the
default generator when adding a new Linux or WSL configuration.
Debug templates for remote CMake debugging: We've simplified the templates
for debugging CMake projects on a remote Linux system or WSL with gdb.
IntelliSense improvements:
IntelliSense now displays more readable type names when dealing with the
Standard Library.
We've added the ability to toggle whether Enter, Space, and Tab function as
commit characters, and to toggle whether Tab is used to Insert Snippet. Find
these settings under Tools > Options > Text Editor > C/C++ > Advanced >
IntelliSense.
Connection Manager over the command line: You can now interact with your
stored remote connections over the command line. It's useful for tasks such as
provisioning a new development machine or setting up Visual Studio in continuous
integration.
Debug and deploy for WSL: Use Visual Studio's native support for WSL to
separate your build system from your remote deploy system. Now you can build
natively on WSL and deploy the build artifacts to a second remote system for
debugging. This workflow is supported by both CMake projects and MSBuild-
based Linux projects.
Support for FIPS 140-2 compliance mode: Visual Studio now supports FIPS 140-2
compliance mode when developing C++ applications that target a remote Linux
system.
Language services for CMake Language files and better CMake project
manipulation:
The source file copy for CMake projects targeting a remote Linux system has
been optimized. Visual Studio now keeps a "fingerprint file" of the last set of
sources copied remotely and optimizes behavior based on the number of files
that have changed.
Code navigation features such as Go To Definition and Find All References are
now supported for functions, variables, and targets in CMake script files.
Add, remove, and rename source files and targets in your CMake projects from
the IDE without manually editing your CMake scripts. When you add or remove
files with the Solution Explorer, Visual Studio will automatically edit your CMake
project. You can also add, remove, and rename the project's targets from the
Solution Explorer's Targets View.
Linux project improvements: Visual Studio Linux projects now have more accurate
IntelliSense and allow you to control remote header synchronization on a project-
by-project basis.
Code Analysis now natively supports Clang-Tidy for both MSBuild and CMake
projects, whether you're using a Clang or MSVC toolset. clang-tidy checks can run
as part of background code analysis, appear as in-editor warnings (squiggles), and
display in the Error List.
Visual Studio CMake projects now have Overview Pages to help you get started
with cross-platform development. These pages are dynamic and help you connect
to a Linux system and add a Linux or WSL configuration to your CMake project.
The launch dropdown menu for CMake projects now displays your most recently
used targets and can be filtered.
C++/CLI now supports interop with .NET Core 3.1 and higher on Windows.
You can now enable ASan for projects compiled with MSVC on Windows for
runtime instrumentation of C++ code that helps with detection of memory errors.
A new collection of tools named C++ Build Insights is now available. For more
information about the announcement, see the C++ Team Blog .
C++ developers can now toggle line comments using the keyboard shortcut
Ctrl+K, Ctrl+/.
IntelliSense member lists are now filtered based on type qualifiers, for example,
const std::vector now filters out methods such as push_back .
New C++ Core Guideline checks , including the new "Enum Rules" rule set, and
additional const , enum , and type rules.
Configure debug targets and custom tasks with environment variables using
CMakeSettings.json or CppProperties.json or the new "env" tag on individual
targets and tasks in launch.vs.json and tasks.vs.json.
Users can now use a quick action on missing vcpkg packages to automatically
open a console and install to the default vcpkg installation.
The remote header copy done by Linux projects (CMake and MSBuild) has been
optimized and now runs in parallel.
Visual Studio's native support for WSL now supports parallel builds for MSBuild-
based Linux projects.
Users can now specify a list of local build outputs to deploy to a remote system
with Linux Makefile projects.
Setting descriptions in the CMake Settings Editor now contain more context and
links to helpful documentation.
The C++ base model for IntelliCode is now enabled by default. You can change
this setting by going to Tools > Options > IntelliCode.
For local CMake projects configured with Clang, Code Analysis now runs clang-tidy
checks, appearing as part of background code analysis as in-editor warnings
(squiggles) and in the Error List.
Windows SDK is no longer a dependency for the CMake for Windows and CMake
for Linux components.
Improvements to the C++ linker to significantly improve iteration build times for
the largest of input. /DEBUG:FAST and /INCREMENTAL times are on average twice as
fast, and /DEBUG:FULL is now three to six times faster.
C++ compiler
These C++20 features have been implemented in the C++ compiler, available
under /std:c++latest (or /std:c++20 starting in Visual Studio 2019 version 16.11):
Increased ability to find function templates via argument-dependent lookup for
function call expressions with explicit template arguments (P0846R0 ).
Designated initialization (P0329R4 ), which allows specific members to be
selected in aggregate initialization, for example, by using the Type t { .member
= expr } syntax.
) mode, the new parser can be enabled by using /Zc:lambda in Visual Studio 2019
version 16.9 or later (previously available as /experimental:newLambdaProcessor
beginning in Visual Studio 2019 version 16.3), for example, /std:c++17 /Zc:lambda .
size_type .
C++ IDE
IntelliCode now ships as an optional component in the Desktop Development with C++
workload. For more information, see Improved C++ IntelliCode now Ships with Visual
Studio 2019 .
IntelliCode uses its own extensive training and your code context to put what you're
most likely to use at the top of your completion list. It can often eliminate the need to
scroll down through the list. For C++, IntelliCode offers the most help when using
popular libraries such as the standard library.
The new IntelliCode features (Custom Models, C++ support, and EditorConfig inference)
are disabled by default. To enable them, go to Tools > Options > IntelliCode > General.
This version of IntelliCode has improved accuracy and includes support for free-
functions. For more information, see AI-Assisted Code Completion Suggestions Come to
C++ via IntelliCode .
The Quick Info tooltip now respects the semantic colorization of your editor. It also
has a new Search Online link that will search online documentation for information
about the hovered code construct. The link provided by Quick Info for red-
squiggled code will search for the error online. That way you don't need to retype
the message into your browser. For more information, see Quick Info
Improvements in Visual Studio 2019: Colorization and Search Online .
General improvements
The Template Bar can populate the dropdown menu based on instantiations of
that template in your codebase.
Lightbulbs for missing #include directives that vcpkg can install, and
autocompletion of available packages for the CMake find_package directive.
The General Property Page for C++ projects has been revised. Some options are
now listed under a new Advanced page. The Advanced page also includes new
properties for your preferred toolset architecture, debug libraries, the MSVC
toolset minor version, and Unity (jumbo) builds.
CMake support
We updated the CMake version that ships with Visual Studio to 3.14. This version
adds built-in support for MSBuild generators targeting Visual Studio 2019 projects
as well as file-based IDE integration APIs.
We've added improvements to the CMake Settings Editor, including support for
Windows Subsystem for Linux (WSL) and configurations from existing caches,
changes to the default build and install roots, and support for environment
variables in Linux CMake configurations.
Completions and quick info for built-in CMake commands, variables, and
properties make it easier to edit your CMakeLists.txt files.
We've integrated support for editing, building, and debugging CMake projects
with Clang/LLVM. For more information, see Clang/LLVM Support in Visual
Studio .
Linux and the Windows Subsystem for Linux
We now support AddressSanitizer (ASan) in Linux and CMake cross-platform
projects. For more information, see AddressSanitizer (ASan) for the Linux Workload
in Visual Studio 2019 .
We've integrated Visual Studio support for using C++ with the Windows
Subsystem for Linux (WSL). Now you can use your local Windows Subsystem for
Linux (WSL) installation with C++ natively in Visual Studio without additional
configuration or a SSH connection. For more information, see C++ with Visual
Studio 2019 and Windows Subsystem for Linux (WSL) .
Code Analysis
New quick fixes for uninitialized variable checks were added. Code Analysis
warnings C6001: using uninitialized memory <variable> and C26494
VAR_USE_BEFORE_INIT are available in the lightbulb menu on relevant lines.
They're enabled by default in the Microsoft Native Minimum ruleset and C++ Core
Check Type rulesets, respectively. For more information, see New code analysis
quick fixes for uninitialized memory (C6001) and use before init (C26494)
warnings .
Remote builds
Users can now separate remote build machines from remote debug machines
when targeting Linux in both MSBuild and CMake projects.
The improved logging for remote connections makes it easier to diagnose issues in
cross-platform development.
C++ compiler
Enhanced support for C++17 features and correctness fixes, plus experimental
support for C++20 features such as modules and coroutines. For detailed
information, see C++ Conformance Improvements in Visual Studio 2019.
The /std:c++latest option now includes C++20 features that aren't necessarily
complete, including initial support for the C++20 operator <=> ("spaceship") for
three-way comparison.
The C++ compiler switch /Gm is now deprecated. Consider disabling the /Gm
switch in your build scripts if it's explicitly defined. However, you can also safely
ignore the deprecation warning for /Gm , because it's not treated as an error when
using "Treat warnings as errors" (/WX).
As MSVC begins implementing features from the C++20 standard draft under the
/std:c++latest flag, /std:c++latest is now incompatible with /clr (all flavors),
/ZW , and /Gm . In Visual Studio 2019, use /std:c++17 or /std:c++14 modes when
Precompiled headers are no longer generated by default for C++ console and
desktop apps.
Improved analysis with /Qspectre for providing mitigation assistance for Spectre Variant
1 (CVE-2017-5753 ). For more information, see Spectre Mitigations in MSVC .
Clang-Format has been applied to the C++ standard library headers for improved
readability.
Because Visual Studio now supports Just My Code for C++, the standard library no
longer needs to provide custom machinery for std::function and std::visit to
achieve the same effect. Removing that machinery largely has no user-visible
effects. One exception is that the compiler will no longer produce diagnostics that
indicate issues on line 15732480 or 16707566 of <type_traits> or <variant> .
Added basic support for OpenMP SIMD vectorization. You can enable it using the
new compiler switch /openmp:experimental . This option allows loops annotated
with #pragma omp simd to potentially be vectorized. The vectorization isn't
guaranteed, and loops annotated but not vectorized will get a warning reported.
No SIMD clauses are supported; they're ignored, and a warning is reported.
We've added support for Short Vector Math Library (SVML) intrinsic functions.
These functions compute the 128-bit, 256-bit, or 512-bit vector equivalents. We
added them to support hand vectorization of loops with calls to math library
functions, and certain other operations like integer division. See the Intel Intrinsic
Guide for definitions of the supported functions.
Optimized the standard library physical design to avoid compiling parts of the
standard library not directly included. This change cut the build time of an empty
file that includes only <vector> in half. As a consequence, you may need to add
#include directives for headers that were previously indirectly included. For
example, code that uses std::out_of_range may now need to add #include
<stdexcept> . Code that uses a stream insertion operator may now need to add
#include <ostream> . The benefit is that only translation units actually using
<stdexcept> or <ostream> components pay the throughput cost to compile them.
if constexpr was applied in more places in the standard library for improved
throughput and reduced code size in copy operations, in permutations like reverse
and rotate, and in the parallel algorithms library.
The standard library now internally uses if constexpr to reduce compile times,
even in C++14 mode.
The runtime dynamic linking detection for the parallel algorithms library no longer
uses an entire page to store the function pointer array. Marking this memory read-
only was considered no longer relevant for security purposes.
The std::thread constructor no longer waits for the thread to start, and no longer
inserts so many layers of function calls between the underlying C library
_beginthreadex and the supplied callable object. Previously std::thread put six
functions between _beginthreadex and the supplied callable object. This number
has been reduced to only three, two of which are just std::invoke . This change
also resolves an obscure timing bug, where a std::thread constructor would stop
responding if the system clock changed at the exact moment the std::thread was
being created.
The standard library now uses destructors instead of catch blocks in several places
to achieve correctness. This change results in better debugger interaction:
Exceptions you throw through the standard library in the affected locations now
show up as being thrown from their original throw site, rather than our rethrow.
Not all standard library catch blocks were eliminated. We expect the number of
catch blocks to be reduced in later releases of MSVC.
Several std::list members were changed to reuse list nodes where possible
rather than deallocating and reallocating them. For example, given a list<int>
that already has a size of 3, a call to assign(4, 1729) now overwrites the int
values in the first three list nodes, and allocates one new list node with the value
1729.
std::vector now initializes and erases elements more efficiently in certain cases.
C++ IDE
Live Share now supports C++, allowing developers using Visual Studio or Visual Studio
Code to collaborate in real time. For more information, see Announcing Live Share for
C++: Real-Time Sharing and Collaboration
Template IntelliSense
The Template Bar now uses the Peek Window UI rather than a modal window, supports
nested templates, and pre-populates any default arguments into the Peek Window. For
more information, see Template IntelliSense Improvements for Visual Studio 2019
Preview 2 . A Most Recently Used dropdown in the Template Bar enables you to
quickly switch between previous sets of sample arguments.
When launching the IDE, a new Start window appears. It has options to open recent
projects, clone code from source control, open local code as a solution or a folder, or
create a new project. The New Project dialog has also been overhauled into a search-
first, filterable experience.
We've modified several project template names and descriptions to fit with the updated
New Project dialog.
For more information, see C++ Productivity Improvements in Visual Studio 2019 Preview
2 .
CMake support
Support for CMake 3.14
Visual Studio can now open existing CMake caches generated by external tools,
such as CMakeGUI, customized meta-build systems or build scripts that invoke
cmake.exe themselves.
Visual Studio helps bootstrap your C++ development with CMake on Linux by
detecting if you have a compatible version of CMake on your Linux machine. If not,
it offers to install it for you.
The vcpkg toolchain is automatically detected and enabled for CMake projects that
are opened in the IDE once vcpkg integrate install has been run. This behavior
can be turned off by specifying an empty toolchain file in CMakeSettings.
Clearer build and configure 'begin' and 'end' messages for CMake projects and
support for Visual Studio's build progress UI. Additionally, there's now a CMake
verbosity setting in Tools > Options to customize the detail level of CMake build
and configuration messages in the Output Window.
IncrediBuild integration
IncrediBuild is included as an optional component in the Desktop development with
C++ workload. The IncrediBuild Build Monitor is fully integrated in the Visual Studio IDE.
For more information, see Visualize your build with IncrediBuild's Build Monitor and
Visual Studio 2019 .
Debugging
For C++ applications running on Windows, PDB files now load in a separate 64-bit
process. This change addresses a range of crashes caused by the debugger
running out of memory. For example, when debugging applications that contain a
large number of modules and PDB files.
The Windows 8.1 Software Development Kit (SDK) is no longer available in the
Visual Studio installer. We recommend you upgrade your C++ projects to the
latest Windows SDK. If you have a hard dependency on 8.1, you can download it
from the Windows SDK archive.
Windows XP targeting will no longer be available for the latest C++ toolset. XP
targeting with VS 2017-level MSVC compiler & libraries is still supported and can
be installed via "Individual components."
Our documentation actively discourages usage of Merge Modules for Visual C++
Runtime deployment. We're taking the extra step this release of marking our
MSMs as deprecated. Consider migrating your VCRuntime central deployment
from MSMs to the redistributable package.
Code analysis
Code analysis now runs automatically in the background. Warnings display as
green squiggles in-editor as you type. For more information, see In-editor code
analysis in Visual Studio 2019 Preview 2 .
Unit testing
The Managed C++ Test Project template is no longer available. You can continue using
the Managed C++ Test framework in your existing projects. For new unit tests, consider
using one of the native test frameworks for which Visual Studio provides templates
(MSTest, Google Test), or the Managed C# Test Project template.
What's new for C++ in Visual Studio
2017
Article • 10/25/2021
Visual Studio 2017 brings many updates and fixes to the C++ environment. We've fixed
over 250 bugs and reported issues in the compiler and tools. Many were submitted by
customers through the Report a Problem and Provide a Suggestion options under Send
Feedback. Thank you for reporting bugs!
For more information on what's new in all of Visual Studio, see What's new in Visual
Studio 2017. For information on what's new for C++ in Visual Studio 2019, see What's
new for C++ in Visual Studio 2019. For information on what's new for C++ in Visual
Studio 2015 and earlier versions, see Visual C++ What's New 2003 through 2015. For
information about what's new in the C++ docs, see Microsoft C++ docs: What's new.
The compiler supports about 75% of the features that are new in C++17, including
structured bindings, constexpr lambdas, if constexpr , inline variables, fold expressions,
and adding noexcept to the type system. These features are available under the
/std:c++17 option. For more information, see C++ Conformance Improvements in
Visual Studio 2017
The MSVC compiler toolset in Visual Studio version 15.7 now conforms with the C++
Standard. For more information, see Announcing: MSVC Conforms to the C++
Standard and Microsoft C/C++ language conformance.
Visual Studio 2017 version 15.8
/debug:fastlink: Enable up to 30% faster incremental link times (vs. Visual Studio
2015) by not copying all debug information into the PDB file. The PDB file instead
points to the debug information for the object and library files used to create the
executable. See Faster C++ build cycle in VS "15" with /Debug:fastlink and
Recommendations to speed C++ builds in Visual Studio .
Visual Studio 2017 allows using /sdl with /await. We removed the /RTC limitation
with Coroutines.
/std:c++17 enables the set of C++17 features implemented by the compiler. This
option disables compiler and standard library support for features after C++17:
ones that are changed or new in later versions of the Working Draft, and defect
updates of the C++ Standard. To enable those features, use /std:c++latest .
instead. For more information, see yield keyword to become co_yield in VS 2017 .
Visual C++ runtime performance continues to improve through better generated code
quality. Now you can just recompile your code, and your app runs faster. Some of the
compiler optimizations are brand new, such as the vectorization of conditional scalar
stores, the combining of calls sin(x) and cos(x) into a new sincos(x) , and the
elimination of redundant instructions from the SSA optimizer. Other compiler
optimizations are improvements to existing functionality, such as: vectorizer heuristics
for conditional expressions, better loop optimizations, and float min/max codegen. The
linker has a new and faster /OPT:ICF implementation, which can result in up to 9% link-
time speedups, and there are other perf fixes in incremental linking. For more
information, see /OPT (Optimizations) and /INCREMENTAL (Link Incrementally).
The Microsoft C++ compiler supports Intel's AVX-512. It has Vector Length instructions
that bring new functions in AVX-512 to 128-bit and 256-bit wide registers.
The /Zc:noexceptTypes- option can be used to revert to the C++14 version of noexcept
while using C++17 mode in general. This option enables you to update your source
code to conform to C++17 without having to rewrite all your throw() code at the same
time. For more information, see Dynamic exception specification removal and noexcept.
Correctness Improvements
There are more standard library improvements in Visual Studio 2017 RTM. For a
complete list, see the C++ Team Blog entry Standard Library Fixes In VS 2017 RTM .
Visual Studio 2017 version 15.3
change ensures that the result of distance() on iterators from that container is
representable in the return type of distance() .
Fixed missing specialization auto_ptr<void> .
The for_each_n() , generate_n() , and search_n() algorithms previously failed to
compile if the length argument wasn't an integral type. They now attempt to
convert nonintegral lengths to the iterators' difference_type .
normal_distribution<float> no longer emits warnings inside the standard library
about narrowing from double to float.
Fixed some basic_string operations that used npos instead of max_size() when
checking for maximum size overflow.
condition_variable::wait_for(lock, relative_time, predicate) would wait for
the entire relative time if there was a spurious wake. Now it waits for only a single
interval of the relative time.
future::get() now invalidates the future , as the standard requires.
iterator_traits<void *> used to be a hard error because it attempted to form
propagate_on_container_swap .
std::decay now handles abominable function types, that is, function types that are
standard requires.
Attempts to avoid magic statics in version 15.3 are repaired in version 15.5.
std::atomic<T> no longer requires T to be default constructible.
Heap algorithms that take logarithmic time behave differently when iterator
debugging is enabled. They no longer do a linear time assertion that the input is in
fact a heap.
__declspec(allocator) is now guarded for C1XX only, to prevent warnings from
types, that is, types whose alignment is greater than max_align_t , unless disabled
by /Zc:alignedNew- . For example, vectors of objects with 16-byte or 32-byte
alignment are now properly aligned for SSE and AVX instructions.
Conformance improvements
We added <any>, <string_view>, apply() , make_from_tuple() .
Added <optional>, <variant>, shared_ptr::weak_type , and <cstdalign>.
Enabled C++14 constexpr in min(initializer_list) , max(initializer_list) , and
minmax(initializer_list) , and min_element() , max_element() , and
minmax_element() .
Several other C++17 features have been implemented. For more information, see
Microsoft C++ language conformance table.
Implemented P0602R0 "variant and optional should propagate copy/move
triviality".
The standard library now officially tolerates dynamic RTTI being disabled via the
/GR- option. Both dynamic_pointer_cast() and rethrow_if_nested() inherently
require dynamic_cast , so the standard library now marks them as =delete under
/GR- .
Even when dynamic RTTI is disabled via /GR- , "static RTTI" in the form of
typeid(SomeType) is still available, and powers several standard library
components. The standard library now supports disabling this feature too, via
/D_HAS_STATIC_RTTI=0 . This flag also disables std::any , the target() and
Several standard library features have been added, deprecated, or removed per the
C++17 standard. For more information, see C++ conformance improvements in
Visual Studio.
Experimental support for the following parallel algorithms:
all_of
any_of
for_each
for_each_n
none_of
reduce
replace
replace_if
sort
The signatures for the following parallel algorithms are added but not parallelized
at this time. Profiling showed no benefit in parallelizing algorithms that only move
or permute elements:
copy
copy_n
fill
fill_n
move
reverse
reverse_copy
rotate
rotate_copy
swap_ranges
<memory_resource>
Library Fundamentals V1
Deleting polymorphic_allocator assignment
Improving class template argument deduction
hypot(x,y,z)
Avoiding unnecessary decay
Mathematical special functions
constexpr char_traits
strings' contents.
Removed control coupling in basic_string , which was difficult for the compiler
optimizer to analyze. For all short strings, calling reserve still has a nonzero cost to
do nothing.
std::vector was overhauled for correctness and performance: aliasing during
(SEH).
Changed the standard library's internal _Deallocate() function to optimize into
smaller code, allowing it to be inlined into more places.
Changed std::try_lock() to use pack expansion instead of recursion.
Improved the std::lock() deadlock avoidance algorithm to use lock()
operations instead of spinning on try_lock() on all the locks.
Enabled the Named Return Value Optimization in system_category::message() .
conjunction and disjunction now instantiate N + 1 types, instead of 2N + 2
types.
std::function no longer instantiates allocator support machinery for each type-
erased callable, improving throughput and reducing .obj size in programs that pass
many distinct lambdas to std::function .
allocator_traits<std::allocator> contains manually inlined std::allocator
operations, reducing code size in code that interacts with std::allocator through
allocator_traits only (that is, in most code).
The C++11 minimal allocator interface is now handled by the standard library
calling allocator_traits directly, instead of wrapping the allocator in an internal
class _Wrap_alloc . This change reduces the code size generated for allocator
support, improves the optimizer's ability to reason about standard library
containers in some cases, and provides a better debugging experience (as now you
see your allocator type, rather than _Wrap_alloc<your_allocator_type> in the
debugger).
Removed metaprogramming for customized allocator::reference , which
allocators aren't allowed to customize. (Allocators can make containers use fancy
pointers but not fancy references.)
The compiler front end was taught to unwrap debug iterators in range-based for
loops, improving the performance of debug builds.
The basic_string internal shrink path for shrink_to_fit() and reserve() is no
longer in the path of reallocating operations, reducing code size for all mutating
members.
The basic_string internal grow path is no longer in the path of shrink_to_fit() .
The basic_string mutating operations are now factored into non-allocating fast
path and allocating slow path functions, making it more likely for the common no-
reallocate case to be inlined into callers.
The basic_string mutating operations now construct reallocated buffers in the
preferred state rather than resizing in place. For example, an insert at the
beginning of a string now moves the content after the insertion exactly once. It's
moved either down or to the newly allocated buffer. It's no longer moved twice in
the reallocating case, first to the newly allocated buffer and then down.
Operations calling the C standard library in <string> now cache the errno address
to remove repeated interaction with TLS.
Simplified the is_pointer implementation.
Finished changing function-based Expression SFINAE to struct and void_t -based.
Standard library algorithms now avoid postincrementing iterators.
Fixed truncation warnings when using 32-bit allocators on 64-bit systems.
std::vector move assignment is now more efficient in the non-POCMA non-
dispatch to memset and memcmp for std::byte and gsl::byte (and other char-like
enums and enum classes). Since std::copy dispatches using
is_trivially_copyable , it didn't need any changes.
Other libraries
The CPPRestSDK, a cross-platform web API for C++, is updated to version 2.9.0. For
more information, see CppRestSDK 2.9.0 is available on GitHub .
ATL
Several project and code wizards have been rewritten in the signature dialog style.
Add Class now launches the Add Class wizard directly. All of the other items that
were previously here are now available under Add > New Item.
Win32 projects are now under the Windows Desktop category in the New Project
dialog.
The Windows Console and Desktop Application templates now create the
projects without displaying a wizard. There's a new Windows Desktop Wizard
under the same category that displays the same options as the old Win32 Console
Application wizard.
Visual Studio 2017 version 15.5
Several C++ operations that use the IntelliSense engine for refactoring and code
navigation run much faster. The following numbers are based on the Visual Studio
Chromium solution with 3500 projects:
ノ Expand table
Rename 5.3x
IntelliSense
The new SQLite-based database engine is now being used by default. The new
engine speeds up database operations like Go To Definition and Find All
References. It significantly improves initial solution parse time. The setting moved
to Tools > Options > Text Editor > C/C++ > Advanced. (It was formerly under
...C/C++ > Experimental.)
We've added error filtering and help for IntelliSense errors in the error list. Clicking
on the error column now allows for filtering. Also, clicking on the specific errors or
pressing F1 launches an online search for the error message.
Added the ability to filter Member List items by kind.
Find All References (Shift+F12) now helps you get around easily, even in complex
codebases. It provides advanced grouping, filtering, sorting, searching within
results, and (for some languages) colorization, so you can get a clear
understanding of your references. For C++, the new UI includes information about
whether we're reading from or writing to a variable.
The experimental refactoring features Change Signature and Extract Function are
now available by default.
Added an experimental 'Faster project load' feature for C++ projects. The next
time you open a C++ project it will load faster, and the time after that it will load
much faster!
Some of these features are common to other languages, and some are specific to
C++. For more information about these new features, see Announcing Visual
Studio "15" Preview 5 .
Support added for ClangFormat. For more information, see ClangFormat Support
in Visual Studio 2017 .
Improvements to the Open Folder experience. You can customize the experience
through these .json files:
CppProperties.json to customize the IntelliSense and browsing experience.
Tasks.json to customize the build steps.
Launch.json to customize the debugging experience.
C++ IntelliSense works without the need to create a CppProperties.json file in the
root folder. We added a new dropdown to allow users to easily switch between
configurations provided by CMake and CppProperties.json files.
Support added for CMake 3.11, code analysis in CMake projects, Targets view in
Solution Explorer, options for cache generation, and single file compilation. For
more information, see CMake Support in Visual Studio and CMake projects in
Visual Studio.
Windows desktop development
We now provide a more granular installation experience for installing the original C++
workload. We added selectable components that enable you to install just the tools that
you need. The indicated installation sizes for the components listed in the installer UI are
incorrect, and underestimate the total size.
To successfully create Win32 projects in the C++ desktop workload, you must install
both a toolset and a Windows SDK. Install the recommended (selected) components
VC++ 2017 v141 toolset (x86, x64) and Windows 10 SDK (10.0.nnnnn) to make sure it
works. If the necessary tools aren't installed, projects won't be created successfully, and
the wizard stops responding.
The Visual C++ Build tools (previously available as a standalone product) are now
included as a workload in the Visual Studio Installer. This workload installs only the tools
required to build C++ projects without installing the Visual Studio IDE. Both the v140
and v141 toolsets are included. The v141 toolset contains the latest improvements in
Visual Studio 2017 version 15.5. For more information, see Visual Studio Build Tools now
include the VS2017 and VS2015 MSVC Toolsets .
Improvements were made in cross-platform code sharing and type visualization. For
more information, see Linux C++ improvements for cross-platform code sharing and
type visualization .
The Linux workload added support for rsync as an alternative to sftp for
synchronizing files to remote Linux machines.
Support is added for cross compilation targeting ARM microcontrollers. To enable
it in the installation, choose the Linux development with C++ workload and select
the option for Embedded and IoT Development. This option adds the ARM GCC
cross compilation tools and Make to your installation. For more information, see
ARM GCC Cross Compilation in Visual Studio .
Support added for CMake. You can now work on your existing CMake code base
without having to convert it to a Visual Studio project. For more information, see
Configure a Linux CMake Project.
Support added for running remote tasks. This capability allows you to run any
command on a remote system that is defined in Visual Studio's Connection
Manager. Remote tasks also provide the capability to copy files to the remote
system. For more information, see Configure a Linux CMake Project.
When writing new code, you can now use C++/WinRT, a standard C++ language
projection for the Windows Runtime implemented solely in header files. It allows you to
consume and author Windows Runtime APIs using any standards-conformant C++
compiler. C++/WinRT is designed to provide C++ developers with first-class access to
the modern Windows API. For more information, see C++/WinRT.
Starting in build 17025 of the Windows SDK Insider Preview, C++/WinRT is included in
the Windows SDK. For more information, see C++/WinRT is now included the Windows
SDK .
New C++ Core Guidelines checks cover smart pointer correctness, correct use of
global initializers, and flagging uses of constructs like goto and bad casts.
Some warning numbers you might find in 15.3 are no longer available in 15.5.
These warnings were replaced with more specific checks.
Support added for /analyze:ruleset, which lets you specify the code analysis rules
to run.
Support added for more C++ Core Guidelines rules. For more information, see
Using the C++ Core Guidelines checkers.
Google Test Adapter and Boost.Test Adapter are now available as components of the
Desktop Development with C++ workload. They're integrated with Test Explorer. CTest
support is added for CMake projects (using Open Folder), although full integration with
Test Explorer isn't available yet. For more information, see Writing unit tests for C/C++.
For more information, see Boost.Test Unit Testing: Dynamic Library support and New
Item Template .
CodeLens support added for C++ unit test projects. For more information, see
Announcing CodeLens for C++ Unit Testing .
Input & Output for Vertex and Geometry shaders: The ability to view input and
output of vertex shaders and geometry shaders has been one of the most
requested features. It's now supported in the tools. Select the VS or GS stage in the
Pipeline Stages view to start inspecting its input and output in the table below.
Search and filter in the object table: Provides a quick and easy way to find the
resources you're looking for.
Resource History: This new view provides a streamlined way of seeing the entire
modification history of a resource as it was used during the rendering of a
captured frame. To invoke the history for any resource, click the clock icon next to
any resource hyperlink.
It displays the new Resource History tool window, populated with the change
history of the resource.
You can capture frames with full call stack capturing enabled. That lets you quickly
deduce the context of each change event, and inspect it within your Visual Studio
project. Set the full stack capture option in the Visual Studio Tools > Options
dialog under Graphics Diagnostics.
API Statistics: View a high-level summary of API usage in your frame. It's handy for
discovering calls you might not realize you're making at all, or calls you're making
too often. This window is available via View > API Statistics in Visual Studio
Graphics Analyzer.
Memory Statistics: View how much memory the driver allocates for the resources
you create in the frame. This window is available via View > Memory Statistics in
Visual Studio Graphics Analyzer. To copy data to a CSV file for viewing in a
spreadsheet, right-click and choose Copy All.
Frame Validation: The new errors and warnings list provides an easy way to
navigate your event list based on potential issues detected by the Direct3D debug
layer. Click View > Frame Validation in Visual Studio Graphics Analyzer to open
the window. Then click Run Validation to start the analysis. It can take several
minutes to complete, depending on the frame's complexity.
Frame Analysis for D3D12: Use Frame Analysis to analyze draw-call performance
with directed "what-if" experiments. Switch to the Frame Analysis tab and run
analysis to view the report.
GPU Usage Improvements: Open traces can be taken via the Visual Studio GPU
Usage profiler with either GPUView or the Windows Performance Analyzer (WPA)
tool for more detailed analysis. If you have the Windows Performance Toolkit
installed, there are two hyperlinks: one for WPA and another for GPUView, at the
bottom right of the session overview.
Traces you open in GPUView via this link support synchronized VS and GPUView
timeline zooming and panning. A checkbox in VS controls whether synchronization
is enabled or not.
Microsoft C++ docs: What's new for
November 2023 to June 2024
Article • 06/27/2024
This article lists major changes to the Microsoft C++ docs for November 2023 to June
2024.
For what was new in the docs in previous months, see What's new history.
For what's new related to C++ in Visual Studio, see What's new for C++ in Visual
Studio.
For the latest C and C++ conformance with ISO standards status, see C++
conformance improvements in Visual Studio.
Setting the Dialog Box's Background Color - add code example for setting a dialog
box's background color
Unicode and Multibyte Character Set (MBCS) Support - Clarified MBCS support in
unicode-and-multibyte-character-set-mbcs-support.md
Updated articles
C language
New articles
Updated articles
Code quality
New articles
Warning C26459
Warning C26837
Warning C26861
Warning C26862
Warning C26863
Warning C26864
Warning C6392
Warning C6393
Warning C6394
Warning C6396
Warning C6397
Warning C6398
Updated articles
C runtime library
Updated articles
Updated several compiler error and warning topics to include or refine examples.
Updated articles
Updated articles
C++ Conformance improvements, behavior changes, and bug fixes in Visual Studio
2022 - updates for 17.10, added _alignof
Microsoft C++ docs: What's new for August 2023 to November 2023
What's new for C++ in Visual Studio 2022 - updates for 17.10
Compiler warnings that are off by default - add new warning for VS 17.6 - C5266 &
C5267 and add warning level info
Predefined macros - documented __arm_arch macro
/ifcMap
/Zc:checkGwOdr (Enforce Standard C++ ODR violations under /Gw)
/KERNEL (Create kernel mode binary)
Updated articles
Code quality
New articles
Updated articles
Warning C6053
Warning C26478
Warning C26817
Warning C26820
alignas (C++)
Updated articles
C runtime library
Updated articles
C++ Conformance improvements, behavior changes, and bug fixes in Visual Studio
2022 - added conformance updates for 17.7 and 17.8.
What's new for C++ in Visual Studio 2022 - updated what's new in C++.
Feedback
Was this page helpful? Yes No
Microsoft C/C++ in Visual Studio (MSVC) makes conformance improvements and bug
fixes in every release. This article lists the significant improvements by major release,
then by version. To jump directly to the changes for a specific version, use the In this
article links.
For changes in Visual Studio 2019, see C++ conformance improvements in Visual Studio
2019.
For changes in Visual Studio 2017, see C++ conformance improvements in Visual Studio
2017.
For changes in older versions, see Visual C++ What's New 2003 through 2015.
For an in-depth summary of changes made to the Standard Template Library, including
conformance changes, bug fixes, and performance improvements, see STL Changelog
VS 2022 17.11 .
Implemented range_formatter
Per P2286R8 , range_formatter is now implemented. This feature is available when
compiling with /std:c++latest .
For an in-depth summary of changes made to the Standard Template Library, including
conformance changes, bug fixes, and performance improvements, see STL Changelog
VS 2022 17.10 .
C++
// Example 1
struct S
{
template<typename T> operator const T*();
};
void test()
{
S{}.operator int*(); // this is invalid now
S{}.operator const int*(); // this is valid
}
Before:
C++
#ifdef __cplusplus
#include <atomic>
#elif !defined(__STDC_NO_ATOMICS__)
#include <stdatomic.h>
#else
#include <custom_atomics_library.h>
#endif
After:
C++
#ifdef __cplusplus
#include <atomic>
#elifndef __STDC_NO_ATOMICS__
#include <stdatomic.h>
#else
#include <custom_atomics_library.h>
#endif
In versions of Visual C++ before Visual Studio 2022 version 17.9, if the _Alignas
specifier appeared next to a structured type in a declaration, it wasn't applied correctly
according to the ISO-C Standard.
C++
struct Outer
{
_Alignas(32) struct Inner { int i; } member1;
struct Inner member2;
};
static_assert(offsetof(struct Outer, member2)==4, "incorrect alignment");
According to the ISO-C Standard, this code should compile without static_assert
emitting a diagnostic.
The _Alignas directive applies only to the member variable member1 . It must not change
the alignment of struct Inner . However, before Visual Studio 17.9.1, the diagnostic
"incorrect alignment" was emitted. The compiler aligned member2 to an offset of 32
bytes within the struct Outer type.
This is a binary breaking change, so a warning is now emitted when this change takes
effect. Warning C5274 is now emitted at warning level 1 for the previous example:
warning C5274: behavior change: _Alignas no longer applies to the type 'Inner'
Also, in previous versions of Visual Studio, when the _Alignas specifier appeared next to
an anonymous type declaration, it was ignored.
C++
Previously, both static_assert statements failed when compiling this code. Now the
code compiles, but emits the following level 1 warnings:
C++
#pragma warning(error: 4706)
struct S
{
auto mf()
{
if (value = 9)
return value + 4;
else
return value;
}
int value = 9;
};
The compiler now also emits the warning in cases where the function isn't referenced.
Previously, because mf is an inline function that isn't referenced, warning C4706 wasn't
emitted for this code. Now the warning is emitted:
C++
To fix this warning, either use an equality operator, value == 9 , if this is what was
intended. Or, wrap the assignment in parentheses, (value = 9) , if assignment is
intended. Otherwise, since the function is unreferenced, remove it.
For a broader summary of changes made to the Standard Template Library, see STL
Changelog VS 2022 17.9 .
According to the ISO-C Standard, this code should compile without the static_assert
emitting a diagnostic. The _Alignas directive applies only to the member variable
member1 . It must not change the alignment of struct Inner . However, before release
17.9.1 of Visual Studio, the diagnostic "incorrect alignment" was emitted. The compiler
aligned member2 to a 32 byte offset within struct Outer .
Fixing this is a binary breaking change, so when this change in behavior is applied a
warning is emitted. For the preceding code, Warning C5274, " _Alignas no longer
applies to the type 'Inner' (only applies to declared data objects)" is now emitted at
warning level 1.
In previous versions of Visual Studio, _Alignas was ignored when it appeared next to an
anonymous type declaration. For example:
Previously, both static_assert statements failed when compiling this code. The code
now compiles, but with the following level 1 warnings:
__VA_OPT__ was added to C++20 and C23. Previous to its addition, there wasn't a
C++
C23 language
For C23, the following are available when using the /std:clatest compiler switch:
typeof
typeof_unqual
__typeof__
__typeof_unqual__
The C compiler used to accept the /FU option, even though it hasn't support managed
compilation for some time. It now issues an error. Projects that pass this option need to
restrict it to C++/CLI projects only.
For a broader summary of changes made to the C++ Standard Library, see STL
Changelog VS 2022 17.8 .
Implemented views::cartesian_product .
For a broader summary of changes made to the Standard Template Library, see STL
Changelog VS 2022 17.7 .
using conformance
Previously, the using directive could cause names from used namespaces to remain
visible when they shouldn't. This could cause unqualified name lookup to find a name in
a namespace even when there's no using directive active.
C++
namespace A
{
template<typename K, typename T>
auto f2(T t)
{
return f<K>(t); // (1) Unqualified lookup should not find anything
}
}
namespace B
{
template<typename K, typename T>
auto f(T t) noexcept
{ // Previous behavior: This function was erroneously found during
unqualified lookup at (1)
return A::f2<K>(t);
}
}
namespace C
{
template<typename T>
struct S {};
namespace D
{
using namespace B;
void h()
{
D::f<void>(C::S<int>());
}
}
The same underlying issue can cause code that previously compiled to now be rejected:
C++
#include <memory>
namespace Addin {}
namespace Gui
{
using namespace Addin;
}
namespace Addin
{
using namespace std;
}
// This previously compiled, but now emits error C2065 for undeclared name
'allocator'.
// This should be declared as 'std::allocator<T*>' because the using
directive nominating
// 'std' is not active at this point.
template <class T, class U = allocator<T*>>
class resource_list
{
};
namespace Gui
{
typedef resource_list<int> intlist;
}
C++
void f(volatile int& expr)
{
++expr;
}
The compiler produces test.cpp(3): warning C5214: applying '++' to an operand with
a volatile qualified type is deprecated in C++20 .
C++
C++
struct S
{
bool operator==(const S&);
bool operator!=(const S&);
};
bool b = S{} != S{};
The compiler accepts this code, which means that the compiler is more strict with code
such as:
c++
struct S
{
operator bool() const;
bool operator==(const S&);
};
Version 17.5 of the compiler accepts this program. Version 17.6 of the compiler rejects it.
To fix it, add const to operator== to remove the ambiguity. Or, add a corresponding
operator!= to the definition as shown in the following example:
C++
struct S
{
operator bool() const;
bool operator==(const S&);
bool operator!=(const S&);
};
Microsoft C/C++ compiler versions 17.5 and 17.6 accept the previous program, and calls
S::operator== in both versions.
corresponding operator!= is the suggested fix for code that previously compiled in
C++17. For more information, see Programming Model .
The C++ Standard requires the underlying type of an enum to be large enough to hold
all enumerators in that enum . Sufficiently large enumerators can set the underlying type
of the enum to unsigned int , long long , or unsigned long long . Previously, such enum
types always had an underlying type of int in the Microsoft compiler, regardless of
enumerator values.
When enabled, the /Zc:enumTypes option is a potential source and binary breaking
change. It's off by default, and not enabled by /permissive- , because the fix might
affect binary compatibility. Some enumeration types change size when the conformant
fix is enabled. Certain Windows SDK headers include such enumeration definitions.
Example
C++
enum Unsigned
{
A = 0xFFFFFFFF // Value 'A' does not fit in 'int'.
};
int main()
{
// Previously called f<int>, now calls f<unsigned int>.
f(+A);
}
// Previously this enum would have an underlying type of `int`, but Standard
C++ requires this to have
// a 64-bit underlying type. Using /Zc:enumTypes changes the size of this
enum from 4 to 8, which could
// impact binary compatibility with code compiled with an earlier compiler
version or without the switch.
enum Changed
{
X = -1,
Y = 0xFFFFFFFF
};
The C++ Standard specifies that within an enumeration definition of no fixed underlying
type, initializers determine the types of enumerators. Or, for the enumerators with no
initializer, by the type of the previous enumerator (accounting for overflow). Previously,
such enumerators were always given the deduced type of the enumeration, with a
placeholder for the underlying type (typically int ).
When enabled, the /Zc:enumTypes option is a potential source and binary breaking
change. It's off by default, and not enabled by /permissive- , because the fix might
affect binary compatibility. Some enumeration types change size when the conformant
fix is enabled. Certain Windows SDK headers include such enumeration definitions.
Example
C++
enum Enum {
A = 'A',
B = sizeof(A)
};
In this example the enumerator A should have type char before the closing brace of the
enumeration, so B should be initialized using sizeof(char) . Before the /Zc:enumTypes
fix, A had enumeration type Enum with a deduced underlying type int , and B was
initialized using sizeof(Enum) , or 4.
Example
int main()
{
int t = 42;
int* pt = &t;
int* volatile * i = &pt;
fn(i); // Now raises C4090
const int** j = &pt;
fn(j); // No longer raises C4090
}
Warning C5255 only addresses files that, after conversion, contain Unicode bidirectional
characters. This warning applies to UTF-8, UTF-16, and UTF-32 files, so the proper
source-encoding must be provided. This change is a source breaking change.
Example (before/after)
In versions of Visual Studio before Visual Studio 2022 version 17.2, an unterminated
bidirectional character didn't produce a warning. Visual Studio 2022 version 17.2
produces warning C5255:
C++
// bidi.cpp
int main() {
const char *access_level = "user";
// The following source line contains bidirectional Unicode characters
equivalent to:
// if ( strcmp(access_level, "user\u202e \u2066// Check if admin
\u2069 \u2066") ) {
// In most editors, it's rendered as:
// if ( strcmp(access_level, "user") ) { // Check if admin
if ( strcmp(access_level, "user") ) {
// Check if admin
printf("You are an admin.\n");
}
return 0;
}
/* build output
bidi.cpp(8): warning C5255: unterminated bidirectional character
encountered: 'U+202e'
bidi.cpp(8): warning C5255: unterminated bidirectional character
encountered: 'U+2066'
*/
Visual Studio 2022 version 17.2 fixes a bug in <charconv> from_chars() float tiebreaker
rules that produced incorrect results. This bug affected decimal strings that were at the
exact midpoint of consecutive float values, within a narrow range. (The smallest and
largest affected values were 32768.009765625 and 131071.98828125 , respectively.) The
tiebreaker rule wanted to round to "even", and "even" happened to be "down", but the
implementation incorrectly rounded "up" ( double was unaffected.) For more information
and implementation details, see microsoft/STL#2366 .
Example
C++
// from_chars_float.cpp
#include <cassert>
#include <charconv>
#include <cstdio>
#include <string_view>
#include <system_error>
using namespace std;
int main() {
const double dbl = 32768.009765625;
const auto sv = "32768.009765625"sv;
float flt = 0.0f;
const auto result = from_chars(sv.data(), sv.data() + sv.size(), flt);
assert(result.ec == errc{});
printf("from_chars() returned: %.1000g\n", flt);
printf("This rounded %s.\n", flt < dbl ? "DOWN" : "UP");
}
Output
Output
Example
// test__STDC__.c
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
#if __STDC__
int f = _open("file.txt", _O_RDONLY);
_close(f);
#else
int f = open("file.txt", O_RDONLY);
close(f);
#endif
}
*/
This change is a source breaking change. It applies when the off-by-default warning
C5246 is enabled.
Example
In Visual Studio 2022 version 17.2 and later, this code now causes an error:
C++
struct S {
union {
float f[4];
double d[2];
};
};
void f()
{
S s = { 1.0f, 2.0f, 3.14f, 4.0f };
}
C++
void f()
{
S s = { { 1.0f, 2.0f, 3.14f, 4.0f } };
}
This change is a source breaking change. It applies in any mode that uses the new
lambda processor: /Zc:lambda , /std:c++20 , or /std:c++latest .
Example
In Visual Studio 2022 version 17.1 this code now emits an error:
C++
#pragma warning(error:5253)
C++
#pragma warning(error:5253)
Example
int f1(int);
int f2(char*);
int main(void)
{
return (f1 == f2);
}
// Old warning:
// C4028: formal parameter 1 different from declaration
// New warning:
// C4113: 'int (__cdecl *)(char *)' differs in parameter lists from 'int
(__cdecl *)(int)'
Error on a nondependent static_assert
In Visual Studio 2022 version 17.1 and later, if the expression associated with a
static_assert isn't a dependent expression, the compiler evaluates the expression
when it's parsed. If the expression evaluates to false , the compiler emits an error.
Previously, if the static_assert was within the body of a function template (or within
the body of a member function of a class template), the compiler wouldn't perform this
analysis.
This change is a source breaking change. It applies in any mode that implies
/permissive- or /Zc:static_assert . This change in behavior can be disabled by using
Example
In Visual Studio 2022 version 17.1 and later, this code now causes an error:
C++
template<typename T>
void f()
{
static_assert(false, "BOOM!");
}
C++
template<typename>
constexpr bool dependent_false = false;
template<typename T>
void f()
{
static_assert(dependent_false<T>, "BOOM!");
}
With this change, the compiler only emits an error if the function template f is
instantiated.
C++
struct S {
E e : 1;
};
A programmer might expect the class member S::e can hold any of the explicitly
named enum values. Given the number of enumeration elements, it isn't possible. The
bitfield can't cover the range of explicitly provided values of E (conceptually, the
domain of E ). To address the concern that the bitfield width isn't large enough for the
domain of the enumeration, a new (off by default) warning is added to MSVC:
Output
t.cpp(4,5): warning C5249: 'S::e' of type 'E' has named enumerators with
values that cannot be represented in the given bit field width of '1'.
E e : 1;
^
t.cpp(1,38): note: see enumerator 'E::Two' with value '2'
enum class E : unsigned { Zero, One, Two };
^
This compiler behavior is a source and binary breaking change that affects all /std and
/permissive modes.
C++
bool f(int *p)
{
return p >= 0;
}
WG21 paper N3478 removed this oversight. This change is implemented in MSVC.
When the example is compiled by using /permissive- (and /diagnostics:caret ), it
emits the following error:
Output
This compiler behavior is a source and binary breaking change that affects code
compiled using /permissive- in all /std modes.
See also
Microsoft C/C++ language conformance
Feedback
Was this page helpful? Yes No
Microsoft C/C++ in Visual Studio (MSVC) makes conformance improvements and bug
fixes in every release. This article lists the improvements by major release, then by
version. To jump directly to the changes for a specific version, use the list below In this
article.
This document lists the changes in Visual Studio 2019. For a guide to the changes in
Visual Studio 2022, see C++ conformance improvements in Visual Studio 2022. For
changes in Visual Studio 2017, see C++ conformance improvements in Visual Studio
2017. For a complete list of previous conformance improvements, see Visual C++
What's New 2003 through 2015.
7 Note
C++20 features were available only in /std:c++latest mode in Visual Studio 2019
until the C++20 implementation was considered complete. Visual Studio 2019
version 16.11 introduces the /std:c++20 compiler mode. In this article, features that
originally required /std:c++latest mode now work in /std:c++20 mode or later in
the latest versions of Visual Studio. We've updated the documentation to mention
/std:c++20 , even though this option wasn't available when the features were first
released.
The following code compiles without errors in Visual Studio 2017 but raises errors C2280
and C2440 in Visual Studio 2019 under /std:c++20 or /std:c++latest :
C++
struct A
{
A() = delete; // user-declared ctor
};
struct B
{
B() = default; // user-declared ctor
int i = 0;
};
C++
struct S
{
bool operator<=(const S&) const { return true; }
};
To avoid the errors, insert a space in the offending line before the final angle bracket:
U<&S::operator<= > u; .
7 Note
This change only affects Visual Studio 2019 versions 16.0 through 16.8. It was
reverted starting in Visual Studio 2019 version 16.9
Previously, MSVC allowed direct binding of a reference from a type with mismatched cv-
qualifiers below the top level. This binding could allow modification of supposedly const
data referred to by the reference.
The compiler for Visual Studio 2019 versions 16.0 through 16.8 instead creates a
temporary, as was required by the standard at that time. Later, the standard retroactively
changed making the previous behavior of Visual Studio 2017 and earlier correct, and the
behavior of Visual Studio 2019 version 16.0 through 16.8 wrong. Consequently, this
change was reverted starting in Visual Studio 2019 version 16.9.
As an example, in Visual Studio 2017, the following code compiles without warnings. In
Visual Studio 2019 versions 16.0 through 16.8, the compiler raises warning C4172.
Starting with Visual Studio 2019 version 16.9, the code once again compiles without
warnings:
C++
struct X
{
const void* const& PData() const
{
return _pv;
}
void* _pv;
};
int main()
{
X x;
auto p = x.PData(); // C4172 <func:#1 "?PData@X@@QBEABQBXXZ"> returning
address of local variable or temporary
}
The argument to reinterpret_cast isn't one of the contexts in which the address of an
overloaded function is permitted. The following code compiles without errors in Visual
Studio 2017, but in Visual Studio 2019 it raises error C2440:
C++
int main()
{
fp r = reinterpret_cast<fp>(&f); // C2440: cannot convert from
'overloaded-function' to 'fp'
}
C++
int f(int);
int f(float);
using fp = int(*)(int);
int main()
{
fp r = static_cast<fp>(&f); // or just &f;
}
Lambda closures
In C++14, lambda closure types aren't literals. The primary consequence of this rule is
that a lambda may not be assigned to a constexpr variable. The following code
compiles without errors in Visual Studio 2017, but in Visual Studio 2019 it raises error
C2127:
C++
int main()
{
constexpr auto l = [] {}; // C2127 'l': illegal initialization of
'constexpr' entity with a non-constant expression
}
To avoid the error, either remove the constexpr qualifier, or else change the
conformance mode to /std:c++17 or later.
operator<<(std::ostream, nullptr_t)
Feature-test macros
P0941R2 - feature-test macros is complete, with support for __has_cpp_attribute .
Feature-test macros are supported in all standard modes.
produces C3615:
C++
long long i = 0;
constexpr void f() {
int* a = reinterpret_cast<int*>(i); // C3615: constexpr function 'f'
cannot result in a constant expression
}
To avoid the error, remove the constexpr modifier from the function declaration.
C++
std::wstring ws = /* . . . */;
std::string out(ws.begin(), ws.end()); // VS2019 C4244: 'argument':
conversion from 'wchar_t' to 'const _Elem', possible loss of data.
Visual Studio 2019 correctly raises warning C4244. To avoid the warning, you can
initialize the std::string as shown in this example:
C++
C++
To avoid the error in this example, use the += operator with the ToString() method: s
+= E::e.ToString(); .
C++
struct X
{
private:
static inline const int c = 1000;
};
struct Y : X
{
static inline int d = c; // VS2019 C2248: cannot access private member
declared in class 'X'.
};
C++
struct X
{
protected:
static inline const int c = 1000;
};
C4800 reinstated
MSVC used to have a performance warning C4800 about implicit conversion to bool . It
was too noisy and couldn't be suppressed, leading us to remove it in Visual Studio 2017.
However, over the lifecycle of Visual Studio 2017 we got lots of feedback on the useful
cases it was solving. We bring back in Visual Studio 2019 a carefully tailored C4800,
along with the explanatory C4165. Both of these warnings are easy to suppress: either
by using an explicit cast, or by comparison to 0 of the appropriate type. C4800 is an off-
by-default level 4 warning, and C4165 is an off-by-default level 3 warning. Both are
discoverable by using the /Wall compiler option.
C++
bool test(IUnknown* p)
{
bool valid = p; // warning C4800: Implicit conversion from 'IUnknown*'
to bool. Possible information loss
IDispatch* d = nullptr;
HRESULT hr = p->QueryInterface(__uuidof(IDispatch),
reinterpret_cast<void**>(&d));
return hr; // warning C4165: 'HRESULT' is being converted to 'bool'; are
you sure this is what you want?
}
To avoid the warnings in the previous example, you can write the code like this:
C++
bool test(IUnknown* p)
{
bool valid = p != nullptr; // OK
IDispatch* d = nullptr;
HRESULT hr = p->QueryInterface(__uuidof(IDispatch),
reinterpret_cast<void**>(&d));
return SUCCEEDED(hr); // OK
}
C++
void example()
{
struct A
{
int boo(); // warning C4822: Local class member function doesn't
have a body
};
}
C++
// C7510.cpp
// compile using: cl /EHsc /W4 /permissive /std:c++latest C7510.cpp
#include <iostream>
if constexpr (a.val)
{
return 1;
}
else
{
return 2;
}
}
struct X
{
using Type = X;
constexpr static int val = 1;
};
int main()
{
std::cout << f<X>() << "\n";
}
To avoid the error, add the typename keyword to the declaration of a : typename T::Type
a; .
The following code produces C7553 in Visual Studio 2017 15.9 and later versions of
Visual Studio:
C++
#include <cstdio>
int f()
{
int y = 1724;
int x = 0xdeadbeef;
mov eax, x
mov y, eax
}
};
lambda();
return y;
}
To avoid the error, move the assembly code into a named function as shown in the
following example:
C++
#include <cstdio>
int f()
{
int y = 1724;
int x = 0xdeadbeef;
auto lambda = [&]
{
g(x, y);
};
lambda();
return y;
}
int main()
{
std::printf("%d\n", f());
}
std::copy(std::move_iterator<std::vector<int>::iterator>,
found.
std::filesystem::space now accepts relative paths.
std::filesystem::path::lexically_relative is no longer confused by trailing
Worked around the POSIX deletion mode delete function that existed in Windows
10 LTSB 1609, but couldn't actually delete files.
The std::boyer_moore_searcher and std::boyer_moore_horspool_searcher copy
constructors and copy assignment operators now actually copy things.
std::system_category::message() whitespace
message.
behavior when calling standard library algorithms, rather than the behavior of a pointer.
The unordered container reserve function now actually reserves for N elements, as
described in LWG 2156 .
Time handling
Previously, some time values that were passed to the concurrency library would
overflow, for example, condition_variable::wait_for(seconds::max()) . Now fixed,
the overflows changed behavior on a seemingly random 29-day cycle (when
uint32_t milliseconds accepted by underlying Win32 APIs overflowed).
the container's sentinel node with the old allocator, do the POCCA/POCMA
assignment over the old allocator, and then try to acquire the sentinel node from
the new allocator. If this allocation failed, the container was corrupted. It couldn't
even be destroyed, as owning a sentinel node is a hard data structure invariant.
This code was fixed to create the new sentinel node by using the source
container's allocator before destroying the existing sentinel node.
Added the overloads for container merge and extract member functions that
accept rvalue containers. For more information, see P0083 "Splicing Maps And
Sets"
std::basic_istream::read processing of \r\n => \n
std::basic_istream::read was fixed to not write into parts of the supplied buffer
std::bitset constructor
The std::bitset constructor no longer reads the ones and zeroes in reverse order for
large bitsets.
std::pair::operator= regression
char8_t
P0482r6 . C++20 adds a new character type that is used to represent UTF-8 code units.
u8 string literals in C++20 have type const char8_t[N] instead of const char[N] , which
was the case previously. Similar changes have been proposed for the C standard in
N2231 . Suggestions for char8_t backward compatibility remediation are given in
P1423r3 . The Microsoft C++ compiler adds support for char8_t in Visual Studio 2019
version 16.1 when you specify the /Zc:char8_t compiler option. It can be reverted to
C++17 behavior via /Zc:char8_t- . The EDG compiler that powers IntelliSense doesn't
yet support it in Visual Studio 2019 version 16.1. You may see spurious IntelliSense-only
errors that don't affect the actual compilation.
Example
C++
The following example produces deprecation warning C4996 for std::identity (defined
in <type_traits>) in Visual Studio 2017:
C++
#include <type_traits>
using T = std::identity<int>::type;
T x, y = std::identity<T>{}(x);
int i = 42;
long j = std::identity<long>{}(i);
The following example shows how to use the new std::identity (defined in
<functional>) together with the new std::type_identity :
C++
#include <type_traits>
#include <functional>
using T = std::type_identity<int>::type;
T x, y = std::identity{}(x);
int i = 42;
long j = static_cast<long>(i);
The legacy lambda processor compiles this example without warnings, but the new
lambda processor produces error C2760:
C++
void f() {
auto a = [](auto arg) {
decltype(arg)::Type t; // C2760 syntax error: unexpected token
'identifier', expected ';'
};
}
This example shows the correct syntax, now enforced by the compiler:
C++
void f() {
auto a = [](auto arg) {
typename decltype(arg)::Type t;
};
}
Designated initialization
P0329R4 (C++20) Designated initialization allows specific members to be selected in
aggregate initialization by using the Type t { .member = expr } syntax. Requires
/std:c++latest (or /std:c++20 in Visual Studio 2019 version 16.11 and later).
This conversion ranking wasn't implemented correctly before Visual Studio 2019 version
16.1. The conforming behavior may change overload resolution behavior or expose an
ambiguity where one previously wasn't detected.
This compiler behavior change applies to all /std modes and is both a source and
binary breaking change.
The following example demonstrates how compiler behavior changes in 16.1 and later
versions:
C++
#include <type_traits>
struct A {};
struct B : public A {};
int main()
{
// Calls f(unsigned char) in 16.1 and later. Called f(unsigned int) in
earlier versions.
// The conversion from 'E' to the fixed underlying type 'unsigned char'
is better than the
// conversion from 'E' to the promoted type 'unsigned int'.
f(e);
remove() , remove_if() , and unique() for list and forward_list now return
size_type .
constant expression. This behavior change comes from the resolution of Core Working
Group (CWG) CWG 1351 and is enabled in /permissive-. The following example
compiles in Visual Studio 2019 version 16.1 and earlier, but produces C2338 in Visual
Studio 2019 version 16.2:
C++
int main() {
static_assert(noexcept(f()), "f should be noexcept"); // C2338 in 16.2
}
To fix the error, add the noexcept expression to the function declaration:
C++
int main() {
static_assert(noexcept(f()), "f should be noexcept");
}
In Visual Studio 2019 version 16.2 and later, the following code produces a level 4 C5054
warning when the /std:c++latest compiler option is enabled ( /std:c++20 in Visual
Studio 2019 version 16.11 and later):
C++
enum E1 { a };
enum E2 { b };
int main() {
int i = a | b; // warning C5054: operator '|': deprecated between
enumerations of different types
}
C++
enum E1 { a };
enum E2 { b };
int main() {
int i = a | static_cast<int>(b);
}
C++
enum E1 { a };
int main() {
double i = a * 1.1;
}
C++
enum E1 { a };
int main() {
double i = static_cast<int>(a) * 1.1;
}
C++
int main() {
int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };
if (a == b) { return 1; } // warning C5056: operator '==': deprecated
for array types
}
To avoid the warning, you can compare the addresses of the first elements:
C++
int main() {
int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };
if (&a[0] == &b[0]) { return 1; }
}
To determine whether the contents of two arrays are equal, use the std::equal function:
C++
C++
#include <compare>
struct S {
int a;
auto operator<=>(const S& rhs) const {
return a <=> rhs.a;
}
};
bool eq(const S& lhs, const S& rhs) {
return lhs == rhs; // error C2676
}
bool neq(const S& lhs, const S& rhs) {
return lhs != rhs; // error C2676
}
C++
#include <compare>
struct S {
int a;
auto operator<=>(const S& rhs) const {
return a <=> rhs.a;
}
bool operator==(const S&) const = default;
};
bool eq(const S& lhs, const S& rhs) {
return lhs == rhs;
}
bool neq(const S& lhs, const S& rhs) {
return lhs != rhs;
}
C++
#include <iostream>
#include <map>
struct K
{
int a;
string b = "label";
};
struct Comparer {
bool operator() (K a, K b) {
return a.a < b.a;
}
};
K const s1{1};
K const s2{2};
K const s3{3};
int main() {
m.emplace(s1, 1.08);
m.emplace(s2, 3.14);
m.emplace(s3, 5.21);
}
C++
struct Comparer {
bool operator() (K a, K b) const {
return a.a < b.a;
}
};
C++
// stream_extraction.cpp
// compile by using: cl /std:c++latest stream_extraction.cpp
#include <iostream>
#include <iomanip>
int main() {
char x[42];
char* p = x;
std::cin >> std::setw(42);
std::cin >> p; // C2679: binary '>>': no operator found which takes a
right-hand operand of type 'char *' (or there is no acceptable conversion)
}
To avoid the error, use the extraction operator with a char[] variable:
C++
#include <iostream>
#include <iomanip>
int main() {
char x[42];
std::cin >> std::setw(42);
std::cin >> x; // OK
}
C++
#include <chrono>
class Foo {
std::chrono::milliseconds::duration TotalDuration{}; // C3646:
'TotalDuration': unknown override specifier
};
C++
#include <chrono>
class Foo {
std::chrono::milliseconds TotalDuration {};
};
C++
namespace N
{
extern "C" void f(int, int, int, bool);
}
void g()
{
N::f(0, 1, 2, false);
}
To avoid the errors in the previous example, use bool instead of BOOL consistently in
both declarations of f .
C++
namespace N {
int f() { return 42; }
}
C++
namespace N {
int f();
}
namespace N {
int f() { return 42; }
}
C++
int* f(bool* p) {
p = false; // error C2440: '=': cannot convert from 'bool' to 'bool *'
p = 0; // OK
return false; // error C2440: 'return': cannot convert from 'bool' to
'int *'
}
To fix the error, use nullptr instead of false . A literal 0 is still allowed:
C++
int* f(bool* p) {
p = nullptr; // OK
p = 0; // OK
return nullptr; // OK
}
This change can lead to different warning diagnostics being generated, and behavior
differences for arithmetic operations on literals.
The following example shows the new behavior in Visual Studio 2019 version 16.4. The
i variable is now of type unsigned int , so the warning is raised. The high-order bits of
C++
void f(int r) {
int i = 2964557531; // warning C4309: truncation of constant value
long long j = 0x8000000000000000ll >> r; // literal is now unsigned,
shift will fill high-order bits with 0
}
The following example demonstrates how to keep the old behavior and avoid the
warnings and run-time behavior change:
C++
void f(int r) {
int i = 2964557531u; // OK
long long j = (long long)0x8000000000000000ll >> r; // shift will keep high-
order bits
}
C++
template<typename T>
void f(T* buffer, int size, int& size_read);
C++
template<typename T>
void f(T* buffer, int size, int& size_read);
C++
#include <type_traits>
struct S;
template<>
struct std::is_fundamental<S> : std::true_type {};
static_assert(std::is_fundamental<S>::value, "fail");
To avoid the error, define a struct that inherits from the preferred type_trait , and
specialize that:
C++
#include <type_traits>
struct S;
template<typename T>
struct my_is_fundamental : std::is_fundamental<T> {};
template<>
struct my_is_fundamental<S> : std::true_type { };
static_assert(my_is_fundamental<S>::value, "fail");
The compiler no longer rewrites expressions using operator== if they involve a return
type that isn't a bool . The following code now produces error C2088:
C++
struct U {
operator bool() const;
};
struct S {
U operator==(const S&) const;
};
To avoid the error, you must explicitly define the needed operator:
C++
struct U {
operator bool() const;
};
struct S {
U operator==(const S&) const;
U operator!=(const S&) const;
};
C++
#include <compare>
union S {
int a;
char b;
auto operator<=>(const S&) const = default;
};
C++
#include <compare>
union S {
int a;
char b;
auto operator<=>(const S&) const { ... }
};
The compiler will no longer define a defaulted comparison operator if the class contains
a reference member. The following code now produces error C2120:
C++
#include <compare>
struct U {
int& a;
auto operator<=>(const U&) const = default;
};
C++
#include <compare>
struct U {
int& a;
auto operator<=>(const U&) const { ... };
};
C++
int main() {
return S<char>::a;
}
Output
C++
int main() {
return S<char>::a;
}
C++
#define m()
line m(
) line
Output
line line
#line 2
Output
line
line
Per P1857R1 , import and module preprocessor directives have new restrictions on
their syntax. This example no longer compiles:
C++
import // Invalid
m; // error C2146: syntax error: missing ';' before identifier 'm'
C++
import m; // OK
C++
#include <compare>
struct S {
std::strong_equality operator<=>(const S&) const = default;
};
void f() {
nullptr<=>nullptr;
&f <=> &f;
&S::operator<=> <=> &S::operator<=>;
}
Output
To resolve the issue, update to prefer the built-in relational operators and replace the
removed types:
C++
#include <compare>
struct S {
std::strong_ordering operator<=>(const S&) const = default; // prefer
'std::strong_ordering'
};
void f() {
nullptr != nullptr; // use pre-existing builtin operator != or ==.
&f != &f;
&S::operator<=> != &S::operator<=>;
}
One consequence of the new behavior can produce a small breaking change: Code that
called a deleted function wouldn't get diagnosed if it was never needed for code
generation. Now we diagnose it up front.
C++
struct S {
S() = delete;
S(int) { }
};
struct U {
U() = delete;
U(int i): s{ i } { }
S s{};
};
U u{ 0 };
Output
C++
struct S {
S() = delete;
S(int) { }
};
struct U {
U() = delete;
U(int i): s{ i } { }
U u{ 0 };
pointers to those character types outputs the pointer value. Programmers don't find
either case intuitive. They often expect the standard library to transcode the character or
null-terminated character string instead, and to output the result.
The C++20 proposal P1423R3 adds deleted stream insertion operator overloads for
these combinations of stream and character or character pointer types. Under
/std:c++20 or /std:c++latest , the overloads make these insertions ill-formed, instead
of behaving in what is likely an unintended manner. The compiler raises error C2280
when one is found. You can define the "escape hatch" macro
_HAS_STREAM_INSERTION_OPERATORS_DELETED_IN_CXX20 to 1 to restore the old behavior.
(The proposal also deletes stream insertion operators for char8_t . Our standard library
implemented similar overloads when we added char8_t support, so the "wrong"
behavior has never been available for char8_t .)
C++
#include <iostream>
int main() {
const wchar_t cw = L'x', *pw = L"meow";
const char16_t c16 = u'x', *p16 = u"meow";
const char32_t c32 = U'x', *p32 = U"meow";
std::cout << cw << ' ' << pw << '\n';
std::cout << c16 << ' ' << p16 << '\n';
std::cout << c32 << ' ' << p32 << '\n';
std::wcout << c16 << ' ' << p16 << '\n';
std::wcout << c32 << ' ' << p32 << '\n';
}
Output
You can achieve the effect of the old behavior in all language modes by converting
character types to unsigned int , or pointer-to-character types to const void* :
C++
#include <iostream>
int main() {
const wchar_t cw = L'x', *pw = L"meow";
const char16_t c16 = u'x', *p16 = u"meow";
const char32_t c32 = U'x', *p32 = U"meow";
std::cout << (unsigned)cw << ' ' << (const void*)pw << '\n'; // Outputs
"120 0052B1C0"
std::cout << (unsigned)c16 << ' ' << (const void*)p16 << '\n'; //
Outputs "120 0052B1CC"
std::cout << (unsigned)c32 << ' ' << (const void*)p32 << '\n'; //
Outputs "120 0052B1D8"
std::wcout << (unsigned)c16 << ' ' << (const void*)p16 << '\n'; //
Outputs "120 0052B1CC"
std::wcout << (unsigned)c32 << ' ' << (const void*)p32 << '\n'; //
Outputs "120 0052B1D8"
}
Changed return type of std::pow() for std::complex
Previously, the MSVC implementation of the promotion rules for the return type of
function template std::pow() was incorrect. For example, previously
pow(complex<float>, int) returned complex<float> . Now it correctly returns
complex<double> . The fix has been implemented unconditionally for all standards modes
This change can cause compiler errors. For example, previously you could multiply
pow(complex<float>, int) by a float . Because complex<T> operator* expects
arguments of the same type, the following example now emits compiler error C2676:
C++
// pow_error.cpp
// compile by using: cl /EHsc /nologo /W4 pow_error.cpp
#include <complex>
int main() {
std::complex<float> cf(2.0f, 0.0f);
(void) (std::pow(cf, -1) * 3.0f);
}
Output
Change the type of the float multiplicand to double . This argument can be
converted directly to a complex<double> to match the type returned by pow .
In some cases, you can avoid pow entirely. For example, pow(cf, -1) can be
replaced by division.
The warnings trigger on missing case statements, undefined enum , and bad bool switch
statements (that is, ones that contain too many cases). For example:
#include <stdbool.h>
int main() {
bool b = true;
switch (b) {
case true: break;
case false: break;
default: break; // C4809: switch statement has redundant 'default'
label;
// all possible 'case' labels are given
}
}
#include <stdbool.h>
int main() {
bool b = true;
switch (b) {
case true: break;
case false: break;
}
}
This change affects all standards modes of the compiler. In default ( /std:c++14 ) and
/std:c++17 modes, the compiler emits warning C5208 for non-conforming code. If
/permissive- is specified, the compiler emits warning C5208 as an error under
/std:c++14 and emits error C7626 under /std:c++17 . The compiler emits error C7626
The following sample shows the constructs that are no longer allowed in unnamed
structs. Depending on the standards mode specified, C5208 or C7626 errors or warnings
are emitted:
C++
struct B { };
typedef struct : B { // inheriting from 'B'; ill-formed
void f(); // ill-formed
static int i; // ill-formed
struct U {
void f(); // nested class has non-data member; ill-formed
};
int j = 10; // default member initializer; ill-formed
} S;
The code above can be fixed by giving the unnamed class a name:
C++
struct B { };
typedef struct S_ : B {
void f();
static int i;
struct U {
void f();
};
int j = 10;
} S;
C++
public class R {
public void Func(string s) {} // overload 1
public void Func(string s, string s2 = "") {} // overload 2;
}
When this class is imported into C++/CLI, a call to one of the overloads causes an error:
C++
The compiler emits error C2668 because both overloads match this argument list. In the
second overload, the second argument is filled in by the default argument. To work
around this problem, you can delete the redundant overload (1). Or, use the full
argument list and explicitly supply the default arguments.
C++
#include <type_traits>
struct S
{
volatile int m;
};
static_assert(std::is_trivially_copyable_v<S>, "Meow!");
This code doesn't compile in versions of MSVC before Visual Studio 2019 version 16.7.
There's an off-by-default compiler warning that you can use to detect this change. If you
compile the code above by using cl /W4 /w45220 , you'll see the following warning:
Output
C++
struct X { bool b; };
void f(X);
int main() {
f(X { "whoops?" }); // error: conversion from 'const char [8]' to 'bool'
requires a narrowing conversion
To correct this code, either add explicit comparisons to nullptr , or avoid contexts where
narrowing conversions are ill-formed:
C++
struct X { bool b; };
void f(X);
int main() {
f(X { "whoops?" != nullptr }); // Absurd, but OK
In most cases, the error can be fixed by replacing nullptr with false , as shown in this
example:
C++
struct S { bool b; };
void g(bool);
bool h() { return nullptr; } // error, should be 'return false;'
int main() {
bool b1 = nullptr; // error: cannot convert from 'nullptr' to 'bool'
S s { nullptr }; // error: cannot convert from 'nullptr' to 'bool'
g(nullptr); // error: cannot convert argument 1 from 'nullptr' to 'bool'
C++
struct B {
explicit B() {}
};
void f() {
B b1[1]{}; // Error in /permissive-, because aggregate init calls
explicit ctor
B b2[1]; // OK: calls default ctor for each array element
}
C++
In previous versions, the constructor would incorrectly initialize the data member Inner
before the data member v . (The C++ standard requires an initialization order that's the
same as the declaration order of the members). Now that the generated code follows
the standard, the member-init-list is out of order. The compiler generates a warning for
this example. To fix it, reorder the member-initializer-list to reflect the declaration order.
Overload resolution involving integral overloads and
long arguments
The C++ standard requires ranking a long to int conversion as a standard conversion.
Previous MSVC compilers incorrectly rank it as an integral promotion, which ranks
higher for overload resolution. This ranking can cause overload resolution to resolve
successfully when it should be considered ambiguous.
The compiler now considers the rank correctly in /permissive- mode. Invalid code gets
diagnosed properly, as in this example:
C++
int main() {
long x {};
f(x); // error: 'f': ambiguous call to overloaded function
f(static_cast<int>(x)); // OK
}
At the call site, change the type of the passed argument to int . You can either
change the variable type, or cast it.
If there are many call sites, you can add another overload that takes a long
argument. In this function, cast and forward the argument to the int overload.
C++
namespace {
extern int x; // Not a definition, but has internal linkage because of
the anonymous namespace
}
int main()
{
return x; // Use of 'x' that no other translation unit can possibly
define.
}
This program previously incorrectly compiled and linked, but will now emit error C7631.
Output
Such variables must be defined in the same translation unit they're used in. For example,
you can provide an explicit initializer or a separate definition.
Here's an example:
C++
struct W { };
struct X { };
struct Y { };
// With this change this code will fail as Z1 is not a complete class type
struct Z1 : X, check_derived_from<Z1, X>
{
};
// This code failed before and it will still fail after this change
struct Z2 : check_derived_from<Z2, Y>, Y
{
};
// With this change this code will fail as Z3 is not a complete class type
struct Z3 : W
{
check_derived_from<Z3, W> cdf;
};
This behavior change applies to all C++ language modes of MSVC, not just /std:c++20
or /std:c++latest .
C++
void f(E e) {
S s = { e }; // warning: conversion from 'E' to 'int' requires a
narrowing conversion
S s1 = { static_cast<int>(e) }; // Suppress warning with explicit
conversion
}
C++
S f();
void g()
{
auto p1 = &(f()); // The temporary returned by 'f' is destructed after
this statement. So 'p1' points to an invalid object.
const auto &r = f(); // This extends the lifetime of the temporary
returned by 'f'
auto p2 = &r; // 'p2' points to a valid object
}
C++
// common.h
struct S {
template<typename T> void f(T);
template<> void f(int);
};
// a.cpp
#include "common.h"
int main() {}
// b.cpp
#include "common.h"
C++
class Node {
public:
int index() const;
};
template<typename T>
int compare(T x, T y)
{
return x < y ? -1 : (x > y ? 1 : 0);
}
specialization, because String is an abstract class. The only viable candidate would have
been compare(const Node&, const Node&) . However, under C++20 the check for the
abstract class type doesn't happen until the function is called. So, the specialization
compare(String, String) gets added to the set of viable candidates, and it's chosen as
the best candidate because the conversion from const String& to String is a better
conversion sequence than the conversion from const String& to const Node& .
Under C++20, one possible fix for this example is to use concepts; that is, change the
definition of compare to:
C++
template<typename T>
int compare(T x, T y) requires !std::is_abstract_v<T>
{
return x < y ? -1 : (x > y ? 1 : 0);
}
Or, if C++ concepts aren't available, you can fall back to SFINAE:
C++
C++
struct S {
int i;
int j;
};
S s(1, 2);
Most of this feature is additive, that is, code now compiles that didn't compile before.
However, it does change the behavior of std::is_constructible . In C++17 mode this
static_assert fails, but in C++20 mode it succeeds:
C++
If you use this type-trait for control of overload resolution, it can lead to a change in
behavior between C++17 and C++20.
C++
int f(int);
namespace N
{
using ::f;
template<typename T>
T f(T);
}
template<typename T>
void g(T&& t)
{
}
void h()
{
using namespace N;
g(f);
}
The call to g uses an overload set that contains two functions, ::f and N::f . Since
N::f is a function template, the compiler should treat the function argument as a non-
deduced context. It means that, in this case, the call to g should fail, as the compiler can't
deduce a type for the template parameter T . Unfortunately, the compiler didn't discard
the fact that it had already decided that ::f was a good match for the function call.
Instead of emitting an error, the compiler would generate code to call g using ::f as
the argument.
Given that in many cases using ::f as the function argument is what the user expects,
we only emit an error if the code is compiled with /permissive- .
option. Migrating from /await to standard coroutines may require some source
changes.
Non-standard keywords
The old await and yield keywords aren't supported in C++20 mode. Code must use
co_await and co_yield instead. Standard mode also doesn't allow the use of return in
C++
// /await
task f_legacy() {
...
await g();
return n;
}
// /std:c++latest
task f() {
...
co_await g();
co_return n;
}
Types of initial_suspend/final_suspend
Under /await , the promise initial and suspend functions may be declared as returning
bool . This behavior isn't standard. In C++20, these functions must return an awaitable
class type, often one of the trivial awaitable types: std::suspend_always if the function
previously returned true , or std::suspend_never if it returned false .
C++
// /await
struct promise_type_legacy {
bool initial_suspend() noexcept { return false; }
bool final_suspend() noexcept { return true; }
...
};
// /std:c++latest
struct promise_type {
auto initial_suspend() noexcept { return std::suspend_never{}; }
auto final_suspend() noexcept { return std::suspend_always{}; }
...
};
Type of yield_value
In C++20, the promise yield_value function must return an awaitable type. In /await
mode, the yield_value function was permitted to return void , and would always
suspend. Such functions can be replaced with a function that returns
std::suspend_always .
C++
// /await
struct promise_type_legacy {
...
void yield_value(int x) { next = x; };
};
// /std:c++latest
struct promise_type {
...
auto yield_value(int x) { next = x; return std::suspend_always{}; }
};
C++
// /await
struct promise_type_legacy {
void set_exception(std::exception_ptr e) { saved_exception = e; }
...
};
// /std:c++latest
struct promise_type {
void unhandled_exception() { saved_exception = std::current_exception();
}
...
};
C++
// /await
auto my_generator() {
...
co_yield next;
};
// /std:c++latest
#include <experimental/generator>
std::experimental::generator<int> my_generator() {
...
co_yield next;
};
The return type of the promise return_value function must be void . In /await mode,
the return type can be anything, and is ignored. This diagnostic can help detect subtle
errors, such as when the author incorrectly assumes the return value of return_value is
returned to a caller.
C++
// /await
struct promise_type_legacy {
...
int return_value(int x) { return x; } // incorrect, the return value of
this function is unused and the value is lost.
};
// /std:c++latest
struct promise_type {
...
void return_value(int x) { value = x; }; // save return value
};
In C++20, the compiler attempts to pass the coroutine parameters (if any) to a
constructor of the promise type. If it fails, it retries with a default constructor. In /await
mode, only the default constructor was used. This change can lead to a difference in
behavior if the promise has multiple constructors. Or, if there's a conversion from a
coroutine parameter to the promise type.
C++
struct coro {
struct promise_type {
promise_type() { ... }
promise_type(int x) { ... }
...
};
};
// Under /await the promise gets constructed using the default constructor.
// Under /std:c++latest the promise gets constructed using the 1-argument
constructor.
f1(0);
struct Object {
template <typename T> operator T() { ... } // Converts to anything!
};
// Under /await the promise gets constructed using the default constructor
// Under /std:c++latest the promise gets copy- or move-constructed from the
result of
// Object::operator coro::promise_type().
f2(Object{});
For code that previously compiled under /std:c++latest and requires non-conforming
compiler behaviors, /permissive may be specified to turn off strict conformance mode
in the compiler. The compiler option must appear after /std:c++latest in the
command-line argument list. However, /permissive results in an error if Modules usage
is detected:
error C1214: Modules conflict with non-standard behavior requested via 'option'
ノ Expand table
Option Description
/Zc:twoPhase- Two-phase name lookup is required for C++20 Modules and implied by
/permissive- .
/Zc:hiddenFriend- Standard hidden friend name lookup rules are required for C++20 Modules
and implied by /permissive- .
Option Description
/Zc:lambda- Standard lambda processing is required for C++20 Modules and is implied
by /std:c++20 mode or later.
/Zc:preprocessor- The conforming preprocessor is required for C++20 header unit usage and
creation only. Named Modules don't require this option.
The /experimental:module option is still required to use the std.* Modules that ship
with Visual Studio, because they're not standardized yet.
compiled with /Zc:twoPhase- if the Module was only consumed. This behavior is no
longer supported.
Visual Studio 2019 version 16.9 implements the changed behavior in all /std compiler
modes. However, because it's potentially a source breaking change, it's only supported
if the code is compiled by using /permissive- .
C++
struct A { };
struct B {
explicit B(const A&);
};
void f()
{
A a;
const B& b1(a); // Always an error
const B& b2{ a }; // Allowed before resolution to CWG 2267 was
adopted: now an error
}
Visual Studio 2019 version 16.9 implements the changed behavior in all /std compiler
modes.
C++
class V {
public:
virtual ~V() noexcept(false);
};
class B : virtual V {
virtual void foo () = 0;
// BEFORE: implicitly defined virtual ~B() noexcept(true);
// AFTER: implicitly defined virtual ~B() noexcept(false);
};
class D : B {
virtual void foo ();
// implicitly defined virtual ~D () noexcept(false);
};
Before this change, the implicitly defined destructor for B was noexcept , because only
potentially constructed subobjects get considered. And, base class V isn't a potentially
constructed subobject, because it's a virtual base and B is abstract. However, base
class V is a potentially constructed subobject of class D , and so D::~D is determined to
be noexcept(false) , leading to a derived class with a weaker exception specification
than its base. This interpretation is unsafe. It can lead to incorrect runtime behavior if an
exception gets thrown from a destructor of a class derived from B.
With this change, a destructor is also potentially throwing if it has a virtual destructor
and any virtual base class has a potentially throwing destructor.
Similar types and reference binding
Core Working Group issue CWG 2352 deals with an inconsistency between the
reference binding rules and changes to type similarity. The inconsistency was introduced
in earlier Defect Reports (such as CWG 330 ). This affected Visual Studio 2019 versions
16.0 through 16.8.
With this change, starting in Visual Studio 2019 version 16.9, code that previously bound
a reference to a temporary in Visual Studio 2019 version 16.0 through 16.8 may now
bind directly when the types involved differ only by cv-qualifiers.
Visual Studio 2019 version 16.9 implements the changed behavior in all /std compiler
modes. It's potentially a source breaking change.
C++
int *ptr;
const int *const &f() {
return ptr; // Now returns a reference to 'ptr' directly.
// Previously returned a reference to a temporary and emitted C4172
}
The update may change program behavior that relied on an introduced temporary:
C++
int func() {
int i1 = 13;
int i2 = 23;
return 0;
}
Normally, the MSVC compiler options work on the principle that the last one seen wins.
Unfortunately, it wasn't the case with the /Zc:twoPhase and /Zc:twoPhase- options.
These options were "sticky," so later options couldn't override them. For example:
In this case, the first /Zc:twoPhase option enables strict two-phase name lookup. The
second option is meant to disable the strict conformance mode (it's the opposite of
/permissive- ), but it didn't disable /Zc:twoPhase .
Visual Studio 2019 version 16.9 changes this behavior in all /std compiler modes.
/Zc:twoPhase and /Zc:twoPhase- are no longer "sticky," and later options can override
them.
Visual Studio 2019 version 16.9 changes to conforming behavior in all /std compiler
modes.
C++
C++
#include <compare>
struct S {
auto operator<=>(const S&) const = default;
operator bool() const;
};
bool f(S a, S b) {
return a < b;
}
However, the compiler wouldn't invoke the comparison function the author might
expect. The code above should have rewritten a < b as (a <=> b) < 0 . Instead, the
compiler used the operator bool() user-defined conversion function and compared
bool(a) < bool(b) . In Visual Studio 2019 version 16.9 and later, the compiler rewrites
C++
struct Base {
bool operator==(const Base&) const;
};
candidate is also added: Derived{} == Base{} . Because of the rules in the standard
about which function wins based on conversions, it turns out that the choice between
Base::operator== and Derived::operator== is undecidable. Because the conversion
sequences in the two expressions are no better or worse than each other, the example
code results in an ambiguity.
To resolve the ambiguity, add a new candidate that won't be subject to the two
conversion sequences:
C++
Because of the operator rewriting rules in C++20, it's possible for overload resolution to
find a new candidate that it wouldn't otherwise find in a lower language mode. And, the
new candidate may be a better match than the older candidate. Consider this example:
C++
struct iterator;
struct const_iterator {
const_iterator(const iterator&);
bool operator==(const const_iterator &ci) const;
};
struct iterator {
bool operator==(const const_iterator &ci) const { return ci == *this; }
};
To help in code like the example, the compiler implements a new warning:
$ cl /std:c++latest /c t.cpp
t.cpp
t.cpp(8): warning C5232: in C++20 this comparison calls 'bool
iterator::operator ==(const const_iterator &) const' recursively
C++
struct iterator {
bool operator==(const const_iterator &ci) const { return ci ==
static_cast<const const_iterator&>(*this); }
};
C++
Earlier versions of the compiler would incorrectly convert the argument of f from type
C to an A by using the templated converting constructor of A . Standard C++ requires
use of the conversion operator B::operator A instead. In Visual Studio 2019 version
16.10 and later, the overload resolution behavior is changed to use the correct overload.
This change can also correct the chosen overload in some other situations:
C++
struct Base
{
operator char *();
};
C++
C++
struct S {
S(int, const S*);
S s(4, &s);
The compiler wouldn't declare the variable s until it parsed the whole declaration,
including the constructor arguments. The lookup of the s in the constructor argument
list would fail. In Visual Studio 2019 version 16.10 and later, this example now compiles
correctly.
C++
In earlier versions of the compiler, when it looks up s in the constructor arguments for
the "inner" declaration of s , it finds the previous declaration ("outer" s ) and the code
compiles. Starting in version 16.10, the compiler emits warning C4700 instead. It's
because the compiler now declares the "inner" s before parsing the constructor
arguments. So, the s lookup finds the "inner" s , which hasn't been initialized yet.
C++
// s.h
template<typename T>
struct S {
int f() { return 1; }
};
template<> int S<int>::f() { return 2; }
C++
// s.cpp
#include "s.h"
C++
// main.cpp
#include "s.h"
int main()
{
}
To address the linker error in the above example, add inline explicitly to S<int>::f :
C++
C++
Earlier versions of the compiler would generate these names for the linker:
Console
Surprisingly, the return type would be omitted from g because of other semantic
behavior caused by the local lambda in the function body. This inconsistency made it
difficult to implement exported functions that have a deduced return type: The module
interface requires information about how the body of a function was compiled. It needs
the information to produce a function on the import side that can properly link to the
definition.
The compiler now omits the return type of a deduced return type function. This behavior
is consistent with other major implementations. There's an exception for function
templates: this version of the compiler introduces a new mangled-name behavior for
function templates that have a deduced return type:
C++
The mangled names for auto and decltype(auto) now appear in the binary, not the
deduced return type:
Console
Earlier versions of the compiler would include the deduced return type as part of the
signature. When the compiler included the return type in the mangled name, it could
cause linker issues. Some otherwise well-formed scenarios would become ambiguous to
the linker.
The new compiler behavior can produce a binary breaking change. Consider this
example:
C++
// a.cpp
auto f() { return 1; }
C++
// main.cpp
int f();
int main() { f(); }
In versions before version 16.10, the compiler produced a name for auto f() that
looked like int f() , even though they're semantically distinct functions. That means the
example would compile. To fix the issue, don't rely on auto in the original definition of
f . Instead, write it as int f() . Because functions that have deduced return types are
C++
In Visual Studio 2019 version 16.10 and later, the compiler emits level 4 warning C5240
instead:
Console
To fix this issue, move the attribute to the correct syntactic position:
C++
C++
export module m;
#include <vector>
export
void f(std::vector<int>);
The developer probably didn't intend module m to own the contents of <vector> . The
compiler now emits a warning to help find and fix the issue:
Console
C++
#include <vector>
export module m;
export
void f(std::vector<int>);
C++
static void f() // warning C4505: 'f': unreferenced function with internal
linkage has been removed
{
}
The compiler now also warns about unreferenced auto functions and unreferenced
functions in anonymous namespaces. It emits an off-by-default warning C5245 for both
of the following functions:
C++
namespace
{
void f1() // warning C5245: '`anonymous-namespace'::f1': unreferenced
function with internal linkage has been removed
{
}
}
Here's an example:
C++
struct S1 {
int i, j;
};
struct S2 {
S1 s1;
int k;
};
S2 s2{ { 1, 2 }, 3 };
C++
struct S {
int i;
int j = 2;
};
Earlier versions of the compiler allowed this code to compile, even though S::i isn't
initialized.
To fix this issue, initialize all members before you create a const instance of an object:
C++
struct S {
int i = 1;
int j = 2;
};
In Visual Studio 2019 version 16.11 and later, the compiler now supports the /std:c++20
compiler mode. Previously, C++20 features were available only in /std:c++latest mode
in Visual Studio 2019. C++20 features that originally required /std:c++latest mode
now work in /std:c++20 mode or later in the latest versions of Visual Studio.
See also
Microsoft C/C++ language conformance
Feedback
Was this page helpful? Yes No
Microsoft C/C++ in Visual Studio (MSVC) makes conformance improvements and bug
fixes in every release. This article lists the improvements by major release, then by
version. To jump directly to the changes for a specific version, use list below In this
article.
This document lists the changes in Visual Studio 2017. For a guide to the changes in
Visual Studio 2022, see C++ conformance improvements in Visual Studio 2022. For a
guide to the changes in Visual Studio 2019, see C++ conformance improvements in
Visual Studio 2019. For a complete list of previous conformance improvements, see
Visual C++ What's New 2003 through 2015.
Copy-list-initialization
Visual Studio 2017 correctly raises compiler errors related to object creation using
initializer lists. These errors weren't caught in Visual Studio 2015, and could lead to
crashes or undefined runtime behavior. As per N4594 13.3.1.7p1 , in copy-list-
initialization , the compiler is required to consider an explicit constructor for overload
resolution. However, it must raise an error if that particular overload gets chosen.
The following two examples compile in Visual Studio 2015 but not in Visual Studio 2017.
C++
struct A
{
explicit A(int) {}
A(double) {}
};
int main()
{
A a1 = { 1 }; // error C3445: copy-list-initialization of 'A' cannot use
an explicit constructor
const A& a2 = { 1 }; // error C2440: 'initializing': cannot convert from
'int' to 'const A &'
C++
A a1{ 1 };
const A& a2{ 1 };
C++
// From http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1228
struct MyStore {
explicit MyStore(int initialCapacity);
};
struct MyInt {
MyInt(int i);
};
struct Printer {
void operator()(MyStore const& s);
void operator()(MyInt const& i);
};
void f() {
Printer p;
p({ 23 }); // C3066: there are multiple ways that an object
// of this type can be called with these arguments
}
This example is similar to the previous one but raises a different error. It succeeds in
Visual Studio 2015 and fails in Visual Studio 2017 with C2668.
C++
struct A {
explicit A(int) {}
};
struct B {
B(int) {}
};
int main()
{
f({ 1 }); // error C2668: 'f': ambiguous call to overloaded function
}
Deprecated typedefs
Visual Studio 2017 now issues the correct warning for deprecated typedefs declared in a
class or struct. The following example compiles without warnings in Visual Studio 2015.
It produces C4996 in Visual Studio 2017.
C++
struct A
{
// also for __declspec(deprecated)
[[deprecated]] typedef int inttype;
};
int main()
{
A::inttype a = 0; // C4996 'A::inttype': was declared deprecated
}
constexpr
Visual Studio 2017 correctly raises an error when the left-hand operand of a
conditionally evaluating operation isn't valid in a constexpr context. The following code
compiles in Visual Studio 2015, but not in Visual Studio 2017, where it raises C3615:
C++
template<int N>
struct array
{
int size() const { return N; }
};
To correct the error, either declare the array::size() function as constexpr or remove
the constexpr qualifier from f .
C++
#include <atomic>
#include <memory>
#include <stdio.h>
int main()
{
std::atomic<int> i(0);
printf("%i\n", i); // error C4839: non-standard use of class
'std::atomic<int>'
// as an argument to a variadic function.
// note: the constructor and destructor will not be
called;
// a bitwise copy of the class will be passed as the
argument
// error C2280: 'std::atomic<int>::atomic(const
std::atomic<int> &)':
// attempting to reference a deleted function
struct S {
S(int i) : i(i) {}
S(const S& other) : i(other.i) {}
operator int() { return i; }
private:
int i;
} s(0);
printf("%i\n", s); // warning C4840 : non-portable use of class
'main::S'
// as an argument to a variadic function
}
To correct the error, you can call a member function that returns a trivially copyable
type,
C++
std::atomic<int> i(0);
printf("%i\n", i.load());
or else use a static cast to convert the object before passing it:
C++
For strings built and managed using CString , the provided operator LPCTSTR() should
be used to cast a CString object to the C pointer expected by the format string.
C++
CString str1;
CString str2 = _T("hello!");
str1.Format(_T("%s"), static_cast<LPCTSTR>(str2));
C++
struct S
{
S(int);
operator int();
};
C++
#include <type_traits>
int main()
{
f(10); // C2672: No matching overloaded function found.
}
Expression-SFINAE
To support expression-SFINAE, the compiler now parses decltype arguments when the
templates are declared rather than instantiated. So, if a non-dependent specialization is
found in the decltype argument, it's not deferred until instantiation-time. It's processed
immediately, and any resulting errors are diagnosed at that time.
The following example shows such a compiler error that is raised at the point of
declaration:
C++
#include <utility>
template <class T, class ReturnT, class... ArgsT>
class IsCallable
{
public:
struct BadType {};
C++
C++
value struct V
{
int i = 0; // error C3446: 'V::i': a default member initializer
// isn't allowed for a member of a value class
};
C++
//class1.cs
using System.Reflection;
using System.Runtime.InteropServices;
namespace ClassLibrary1
{
[DefaultMember("Value")]
public class Class1
{
public int Value
{
// using attribute on the return type triggers the compiler bug
[return: MarshalAs(UnmanagedType.I4)]
get;
}
}
[DefaultMember("Value")]
public class Class2
{
public int Value
{
get;
}
}
}
// code.cpp
#using "class1.dll"
In Visual Studio 2017, you can access both Value properties by their name:
C++
#using "class1.dll"
constexpr lambdas
Lambda expressions may now be used in constant expressions. For more information,
see constexpr lambda expressions in C++.
New attribute [[maybe_unused]] silences warnings when an entity isn't used. The
[[nodiscard]] attribute creates a warning if the return value of a function call is
Structured bindings
It's now possible in a single declaration to store a value with individual names for its
components, when the value is an array, a std::tuple or std::pair , or has all public
non-static data members. For more information, see P0144R0 - Structured Bindings
and Returning multiple values from a function.
C++
template<typename T>
struct S {
template<typename U> static int f() = delete;
};
void g()
{
decltype(S<int>::f<int>()) i; // this should fail with
// C2280: 'int S<int>::f<int>(void)': attempting to reference a deleted
function
}
C++
struct S;
enum E;
Now the compiler emits a warning if it finds this error at compile time: a native object
with deleted copy ctor gets passed between a native and managed boundary by value.
For those cases in which the compiler doesn't know at compile time, it injects a runtime
check so that the program calls std::terminate immediately when an ill-formed
marshaling occurs. In Visual Studio 2017 version 15.3, the following code produces
warning C4606:
C++
class A
{
public:
A() : p_(new int) {}
~A() { delete p_; }
private:
int *p_;
};
#pragma unmanaged
void f(A a)
{
}
#pragma managed
int main()
{
// This call from managed to native requires marshaling. The CLR doesn't
// understand C++ and uses BitBlt, which results in a double-free later.
f(A()); // C4606 'A': passing argument by value across native and
managed
// boundary requires valid copy constructor. Otherwise, the runtime
// behavior is undefined.`
}
To fix the error, remove the #pragma managed directive to mark the caller as native and
avoid marshaling.
the compiler produces warning C4698 for this attribute. A few APIs in previous versions
of the Windows SDK have already been decorated with the attribute, and calls to these
APIs now trigger this compiler warning. Newer Windows SDKs have the attribute
removed from all shipped types. If you're using an older SDK, you'll need to suppress
these warnings for all calls to shipped types.
C++
Windows::Storage::IApplicationDataStatics2::GetForUserAsync(); // C4698
// 'Windows::Storage::IApplicationDataStatics2::GetForUserAsync' is for
// evaluation purposes only and is subject to change or removal in future
updates
C++
#pragma warning(push)
#pragma warning(disable:4698)
Windows::Storage::IApplicationDataStatics2::GetForUserAsync();
#pragma warning(pop)
C++
struct S {};
C++
struct S {
template <typename T>
void f(T t);
};
template <typename T>
void S::f(T t) {}
C++
#include <memory>
class B { };
class D : B { }; // C2243: 'type cast': conversion from 'D *' to 'B *'
exists, but is inaccessible
void f()
{
std::unique_ptr<B>(new D());
}
In previous versions of Visual Studio, the following ill-formed code could potentially
cause a runtime crash. Visual Studio 2017 version 15.3 produces warning C5037:
C++
C++
struct A {
int arr[10];
};
To fix the code, either disable the warning with a pragma or change the code to not use
offsetof :
C++
#pragma warning(push)
#pragma warning(disable: 4841)
constexpr auto off = offsetof(A, arr[2]);
#pragma warning(pop)
C++
#include <cstddef>
struct A {
int ten() { return 10; }
static constexpr int two = 2;
};
This code is ill-formed and could potentially cause a crash at runtime. To fix the error,
change the code to no longer invoke undefined behavior. It's non-portable code that's
disallowed by the C++ standard.
compiler would ignore the attribute, which could have runtime implications. When the
/Wall and /WX options are set, the following code produces warning C4768:
C++
C++
This warning is off by default in Visual Studio 2017 version 15.3, and only impacts code
compiled with /Wall /WX . Starting in Visual Studio 2017 version 15.5, it's enabled by
default as a level 3 warning.
In previous versions of Visual Studio, the compiler didn't detect when a call to a deleted
destructor occurred in the context of the expression associated with decltype . In Visual
Studio 2017 version 15.3, the following code produces error C2280:
C++
template<typename T>
struct A
{
~A() = delete;
};
template<typename T>
auto f() -> A<T>;
template<typename T>
auto g(T) -> decltype((f<T>()));
void h()
{
g(42); // C2280: 'A<T>::~A(void)': attempting to reference a deleted
function
}
Uninitialized const variables
Visual Studio 2017 RTW release had a regression: the C++ compiler wouldn't issue a
diagnostic for an uninitialized const variable. This regression has been fixed in Visual
Studio 2017 version 15.3. The following code now produces warning C4132:
C++
Empty declarations
Visual Studio 2017 version 15.3 now warns on empty declarations for all types, not just
built-in types. The following code now produces a level 2 C4091 warning for all four
declarations:
C++
struct A {};
template <typename> struct B {};
enum C { c1, c2, c3 };
The warning is excluded under /Wv:18 and is on by default under warning level W2.
Previous versions of the compiler gave incorrect results for std::is_convertible for array
types. This required library writers to special-case the Microsoft C++ compiler when
using the std::is_convertible<...> type trait. In the following example, the static
asserts pass in earlier versions of Visual Studio but fail in Visual Studio 2017 version 15.3:
C++
#include <type_traits>
static_assert(std::is_convertible<Array, Array>::value);
static_assert(std::is_convertible<const Array, const Array>::value, "");
static_assert(std::is_convertible<Array&, Array>::value, "");
static_assert(std::is_convertible<Array, Array&>::value, "");
C++
C++
#include <type_traits>
class PrivateDtor {
PrivateDtor(int) { }
private:
~PrivateDtor() { }
};
C++
T obj(std::declval<Args>()...)
C++
namespace N {
template<class T>
void f(T&, T&);
template<class T>
void f();
}
template<class T>
void f(T&, T&);
struct S {};
void f()
{
using N::f;
S s1, s2;
f(s1, s2); // C2668: 'f': ambiguous call to overloaded function
}
To fix the code, remove the using N::f statement if you intended to call ::f() .
C++
struct S {};
void f(S, int);
void g()
{
void f(S); // C2660 'f': function does not take 2 arguments:
// or void f(S, int);
S s;
f(s, 0);
}
To fix the problem, either change the f(S) signature or remove it.
C++
struct A
{ // Initialized in reverse, y reused
A(int a) : y(a), x(y) {} // C5038: data member 'A::y' will be
initialized after data member 'A::x'
int x;
int y;
};
To fix the problem, arrange the initializer list to have the same order as the declarations.
A similar warning is raised when one or both initializers refer to base class members.
This warning is off-by-default, and only affects code compiled with /Wall .
not_fn()
Rewording enable_shared_from_this
P0033R1 enable_shared_from_this was added in C++11. The C++17 standard
into the same container or a different container that uses the same node type. (A
common use case is to extract a node from a std::map , change the key, and reinsert.)
shared_ptr<T[]> , shared_ptr<T[N]>
Clarifying insert_return_type
P0508R0 The associative containers with unique keys, and the unordered containers
with unique keys have a member function insert that returns a nested type
insert_return_type . That return type is now defined as a specialization of a type that is
Annex D are marked as deprecated. For more information, see Standard library features
in Annex D are marked as deprecated.
The standard library was updated in response to C++17 compiler changes. Updates
include the addition of noexcept in the type system, and the removal of dynamic-
exception-specifications.
C++
template<typename... T>
int f(T* ...)
{
return 1;
}
template<typename T>
int f(const T&)
{
return 2;
}
int main()
{
int i = 0;
f(&i); // C2668
}
Output
t161.cpp
t161.cpp(16): error C2668: 'f': ambiguous call to overloaded function
t161.cpp(8): note: could be 'int f<int*>(const T &)'
with
[
T=int*
]
t161.cpp(2): note: or 'int f<int>(int*)'
t161.cpp(16): note: while trying to match the argument list '(int*)'
The problem in the example above is that there are two differences in the types (const
vs. non-const and pack vs. non-pack). To eliminate the compiler error, remove one of
the differences. Then the compiler can unambiguously order the functions.
C++
template<typename... T>
int f(T* ...)
{
return 1;
}
template<typename T>
int f(T&)
{
return 2;
}
int main()
{
int i = 0;
f(&i);
}
Exception handlers
Handlers of reference to array or function type are never a match for any exception
object. The compiler now correctly honors this rule and raises a level 4 warning, C4843.
It also no longer matches a handler of char* or wchar_t* to a string literal when
/Zc:strictStrings is used.
C++
int main()
{
try {
throw "";
}
catch (int (&)[1]) {} // C4843 (This should always be dead code.)
catch (void (&)()) {} // C4843 (This should always be dead code.)
catch (char*) {} // This should not be a match under /Zc:strictStrings
}
Output
C++
C++
#include <functional>
#include <iostream>
using namespace std;
int main() {
std::tr1::function<int (int, int)> f = std::plus<int>(); //C4996
cout << f(3, 5) << std::endl;
f = std::multiplies<int>();
cout << f(3, 5) << std::endl;
}
Output
C++
#include <functional>
#include <iostream>
using namespace std;
int main() {
std::function<int (int, int)> f = std::plus<int>();
cout << f(3, 5) << std::endl;
f = std::multiplies<int>();
cout << f(3, 5) << std::endl;
}
In Visual Studio 2017 version 15.5, the following code raises C4996:
C++
#include <iterator>
#include <type_traits>
Output
warning C4996:
'std::iterator<std::random_access_iterator_tag,int,ptrdiff_t,_Ty*,_Ty
&>::pointer': warning STL4015: The std::iterator class template (used as a
base class to provide typedefs) is deprecated in C++17. (The <iterator>
header is NOT deprecated.) The C++ standard has never required user-defined
iterators to derive from std::iterator. To fix this warning, stop deriving
from std::iterator and start providing publicly accessible typedefs named
iterator_category, value_type, difference_type, pointer, and reference. Note
that value_type is required to be non-const, even for constant iterators.
You can define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING or
_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have
received this warning.
To fix the error, follow the instructions in the warning text, as demonstrated in the
following code:
C++
#include <iterator>
class MyIter {
public:
typedef std::random_access_iterator_tag iterator_category;
typedef int value_type;
typedef ptrdiff_t difference_type;
typedef int* pointer;
typedef int& reference;
#include <type_traits>
C++
void f() {
char s[2] = {0}; // C4189. Either use the variable or remove it.
}
Output
Single-line comments
In Visual Studio 2017 version 15.5, warnings C4001 and C4179 are no longer emitted by
the C compiler. Previously, they were only emitted under the /Za compiler switch. The
warnings are no longer needed because single-line comments have been part of the C
standard since C99.
C++
/* C only */
#pragma warning(disable:4001) // C4619
#pragma warning(disable:4179)
// single line comment
//* single line comment */
Output
When the code doesn't need to be backwards compatible, avoid the warning by
removing the C4001 and C4179 suppression. If the code does need to be backward
compatible, then suppress C4619 only.
/* C only */
#pragma warning(disable:4619)
#pragma warning(disable:4001)
#pragma warning(disable:4179)
C++
Output
To fix the error, place the linkage specification before the __declspec attribute:
C++
1. Switch to the latest Windows SDK that came with Visual Studio 2017 version 15.5
release.
2. Turn off the warning around the #include of the Windows SDK header statement:
C++
In earlier versions of Visual Studio, the compiler always gave a constexpr variable
internal linkage even when the variable was marked extern . In Visual Studio 2017
version 15.5, a new compiler switch ( /Zc:externConstexpr ) enables correct, standards-
conforming behavior. Eventually this behavior will become the default.
C++
Output
C++
C++
#include <typeinfo>
struct S;
Output
std::is_convertible requires the target type to be a valid return type. In earlier versions
of Visual Studio, the compiler incorrectly allowed abstract types, which might lead to
incorrect overload resolution and unintended runtime behavior. The following code now
correctly raises C2338:
C++
#include <type_traits>
To avoid the error, when using is_convertible you should compare pointer types
because a non-pointer-type comparison might fail if one type is abstract:
C++
#include <type_traits>
while using C++17 mode in general. It enables you to update your source code to
conform to C++17 without having to rewrite all your throw() code at the same time.
The following code generates C5043 and C5040 in Visual Studio 2017 version 15.5 when
the /std:c++17 switch is applied:
C++
struct A {
virtual void f() throw();
};
struct B : A {
virtual void f() { } // error C2694
};
To remove the errors while still using /std:c++17 , either add the /Zc:noexceptTypes-
switch to the command line, or else update your code to use noexcept , as shown in the
following example:
C++
struct A {
virtual void f() noexcept;
};
struct B : A {
virtual void f() noexcept { }
};
Inline variables
Static constexpr data members are now implicitly inline , which means that their
declaration within a class is now their definition. Using an out-of-line definition for a
static constexpr data member is redundant, and now deprecated. In Visual Studio
2017 version 15.5, when the /std:c++17 switch is applied the following code now
produces warning C5041:
C++
struct X {
static constexpr int size = 3;
};
const int X::size; // C5041: 'size': out-of-line definition for constexpr
static data member is not needed and is deprecated in C++17
exceptions. This behavior is contrary to the C++ standard and can cause undefined
behavior at runtime. The standard requires such functions to be defined as deleted if
there's an exception specification mismatch. Under /std:c++17 , the following code
raises C2280:
C++
struct A {
A& operator=(const A& other) { // No exception specification; this
function may throw.
...
}
};
struct B : public A {
__declspec(nothrow) B& operator=(const B& other) = default;
};
int main()
{
B b1, b2;
b2 = b1; // error C2280: attempting to reference a deleted function.
// Function was implicitly deleted because the explicit
exception
// specification is incompatible with that of the implicit
declaration.
}
To correct this code, either remove __declspec(nothrow) from the defaulted function, or
remove = default and provide a definition for the function along with any required
exception handling:
C++
struct A {
A& operator=(const A& other) {
// ...
}
};
struct B : public A {
B& operator=(const B& other) = default;
};
int main()
{
B b1, b2;
b2 = b1;
}
With noexcept in the type system, partial specializations for matching particular
"callable" types may not compile, or fail to choose the primary template, because of a
missing partial specialization for pointers-to-noexcept-functions.
In such cases, you may need to add more partial specializations to handle the noexcept
function pointers and noexcept pointers to member functions. These overloads are only
legal in /std:c++17 mode or later. If backwards-compatibility with C++14 must be
maintained, and you're writing code that others consume, then you should guard these
new overloads inside #ifdef directives. If you're working in a self-contained module,
then instead of using #ifdef guards you can just compile with the /Zc:noexceptTypes-
switch.
The following code compiles under /std:c++14 but fails under /std:c++17 with error
C2027:
C++
template <>
struct A<void(*)()>
{
static const bool value = true;
};
int main()
{
return g(&f) ? 0 : 1; // C2027: use of undefined type 'A<T>'
}
The following code succeeds under /std:c++17 because the compiler chooses the new
partial specialization A<void (*)() noexcept> :
C++
template <>
struct A<void(*)()>
{
static const bool value = true;
};
template <>
struct A<void(*)() noexcept>
{
static const bool value = true;
};
int main()
{
return g(&f) ? 0 : 1; // OK
}
C++
struct A {
template<typename T>
A(T, typename T::type = 0);
A(int);
};
struct B : A {
using A::A;
B(int n) = delete; // Error C2280
};
C++
struct A {
template<typename T>
A(T, typename T::type = 0);
A(int);
};
struct B : A {
using A::A;
B(int n)
{
//do something
}
};
If the constructor of a base class is non-public, but accessible to a derived class, then
under /std:c++17 mode and later in Visual Studio 2017 version 15.7, you can no longer
use empty braces to initialize an object of the derived type. The following example
shows C++14 conforming behavior:
C++
struct Derived;
struct Base {
friend struct Derived;
private:
Base() {}
};
In C++17, Derived is now considered an aggregate type. It means that the initialization
of Base via the private default constructor happens directly, as part of the extended
aggregate initialization rule. Previously, the Base private constructor was called via the
Derived constructor, and it succeeded because of the friend declaration. The following
example shows C++17 behavior in Visual Studio version 15.7 in /std:c++17 mode:
C++
struct Derived;
struct Base {
friend struct Derived;
private:
Base() {}
};
struct Derived : Base {
Derived() {} // add user-defined constructor
// to call with {} initialization
};
Derived d1; // OK. No aggregate init involved.
Derived d2 {}; // error C2248: 'Base::Base': cannot access
// private member declared in class 'Base'
In /std:c++17 mode, the compiler can now deduce the type of a non-type template
argument that is declared with auto :
C++
One effect of this new feature is that valid C++14 code may not be valid or may have
different semantics. For example, some overloads that were previously invalid are now
valid. The following example shows C++14 code that compiles because the call to
example(p) is bound to example(void*); . In Visual Studio 2017 version 15.7, in
C++
The following example shows C++17 code in Visual Studio 15.7 in /std:c++17 mode:
C++
2019.
C++17: hypot(x, y, z)
P0030R1 Adds three new overloads to std::hypot , for types float , double , and long
double , each of which has three input parameters.
C++17: <filesystem>
P0218R1 Adopts the File System TS into the standard with a few wording
modifications.
Previously, the compiler ignored the default argument in the primary class template:
C++
template<typename T>
struct S {
void f(int = 0);
};
template<typename T>
void S<T>::f(int = 0) {} // Re-definition necessary
In /std:c++17 mode in Visual Studio 2017 version 15.7, the default argument isn't
ignored:
C++
template<typename T>
struct S {
void f(int = 0);
};
template<typename T>
void S<T>::f(int) {} // Default argument is used
In the following example, the compiler in Visual Studio 15.6 and earlier resolves D::type
to B<T>::type in the primary class template.
C++
template<typename T>
struct B {
using type = T;
};
template<typename T>
struct D : B<T*> {
using type = B<T*>::type;
};
Visual Studio 2017 version 15.7, in /std:c++17 mode, requires the typename keyword in
the using statement in D. Without typename , the compiler raises warning C4346:
'B<T*>::type': dependent name is not a type and error C2061: syntax error:
identifier 'type' :
C++
template<typename T>
struct B {
using type = T;
};
template<typename T>
struct D : B<T*> {
using type = typename B<T*>::type;
};
C++
int main() {
f(); // warning C4834: discarding return value
// of function with 'nodiscard'
}
The following code example in Visual Studio 2017 version 15.7 raises error C2614:
C++
template<typename T>
struct B {};
template<typename T>
struct D : B<T>
{
template<typename ...C>
D() : B() {} // C2614: D<int>: illegal member initialization: 'B' is not
a base or member
};
D<int> d;
C++
#include <array>
struct X {
unsigned short a;
unsigned char b;
};
int main() {
constexpr std::array<X, 2> xs = { // C2078: too many initializers
{ 1, 2 },
{ 3, 4 }
};
return 0;
}
In Visual Studio 2017 version 15.7 update 3 and later, the previous example now raises
C2078. The following example shows how to fix the code. When initializing a std::array
with nested brace-init-lists, give the inner array a braced-list of its own:
C++
#include <array>
struct X {
unsigned short a;
unsigned char b;
};
int main() {
constexpr std::array<X, 2> xs = {{ // note double braces
{ 1, 2 },
{ 3, 4 }
}}; // note double braces
return 0;
}
C++
The standard C++ attribute [[deprecated]] may be used instead, and is respected in
Visual Studio 2017 version 15.6. The following code now produces C2760:
C++
To fix the error, change to code to the following (with the attribute placed before the '='
of the alias definition):
C++
One way this can manifest is with lookup into dependent base classes. Previously, the
compiler allowed the use of names that are defined in dependent base classes. It's
because they'd be looked up during instantiation time when all the types are resolved.
Now that code is treated as an error. In these cases, you can force the variable to be
looked up at instantiation time by qualifying it with the base class type or otherwise
making it dependent, for example, by adding a this-> pointer.
C++
7 Note
At some time in the future, Microsoft will move the location where some standard
library types are defined. This change will break existing code that adds forward
declarations to namespace std . A new warning, C4643, helps identify such source
issues. The warning is enabled in /default mode and is off by default. It will affect
programs that are compiled with /Wall or /WX .
C++
namespace std {
template<typename T> class vector; // C4643: Forward declaring 'vector'
// in namespace std is not permitted
// by the C++ Standard`
}
To fix the error, use a #include directive rather than a forward declaration:
C++
#include <vector>
Without this error, the following program will compile but will generate an infinite loop:
C++
class X {
public:
X(int, int);
X(int v) : X(v){} // C7535: 'X::X': delegating constructor calls itself
};
C++
class X {
public:
X(int, int);
X(int v) : X(v, 0) {}
};
In Visual Studio 2017 version 15.8, the compiler constrains the areas that these
reinterpret_cast operators can appear in the default mode, to help code conform to
standard C++ behavior. Under /permissive-, the constraints are even stricter. Using the
result of an offsetof in places that require constant expressions may result in code that
issues warning C4644 or C2975.
The following code raises C4644 in default and /std:c++17 modes, and C2975 in
/permissive- mode:
C++
struct Data {
int x;
};
int main()
{
switch (0) {
case MY_OFFSET(Data, x): return 0; // C4644: usage of the
// macro-based offsetof pattern in constant expressions
// is non-standard; use offsetof defined in the C++
// standard library instead
// OR
// C2975: invalid template argument, expected
// compile-time constant expression
default: return 1;
}
}
C++
#include <cstddef>
struct Data {
int x;
};
int main()
{
switch (0) {
case offsetof(Data, x): return 0;
default: return 1;
}
}
In Visual Studio 2017 version 15.8, in /permissive- mode, the following code raises
C3770:
C++
template<typename... T>
class X : public T... { };
class S { };
int main()
{
X<const S> x; // C3770: 'const S': is not a valid base class
}
In /permissive- mode, the compiler now requires the template keyword to precede a
template-name when it comes after a dependent nested-name-specifier.
C++
template<typename T>
struct X : Base<T>
{
void example()
{
Base<T>::example<int>(); // C7510: 'example': use of dependent
// template name must be prefixed with 'template'
// note: see reference to class template instantiation
// 'X<T>' being compiled
}
};
To fix the error, add the template keyword to the Base<T>::example<int>(); statement,
as shown in the following example:
C++
template<typename T>
struct X : Base<T>
{
void example()
{
// Add template keyword here:
Base<T>::template example<int>();
}
};
when compiled by using /clr , and one of the operands is a field of an object or an
array element.
The compiler emits warning C4866 when it can't guarantee left-to-right evaluation. The
compiler generates this warning only if /std:c++17 or later is specified, as the left-to-
right order requirement of these operators was introduced in C++17.
To resolve this warning, first consider whether left-to-right evaluation of the operands is
necessary. For example, it could be necessary when evaluation of the operands might
produce order-dependent side-effects. The order in which operands are evaluated has
no observable effect in many cases. If the order of evaluation must be left-to-right,
consider whether you can pass the operands by const reference instead. This change
eliminates the warning in the following code sample:
C++
// C4866.cpp
// compile with: /w14866 /std:c++17
class HasCopyConstructor
{
public:
int x;
HasCopyConstructor(int x) : x(x) {}
HasCopyConstructor(const HasCopyConstructor& h) : x(h.x) { }
};
int main()
{
HasCopyConstructor a{ 1 };
HasCopyConstructor b{ 2 };
In previous versions of the compiler, the following code was allowed. In Visual Studio
2017 version 15.9, in /permissive- mode, the compiler raises C3861:
C++
private:
template <template <typename...> typename Type, typename... Args>
static constexpr A<Args...> from_template(A<Type<Args...>>);
};
A<>::from_template_t<A<int>> a;
Modules changes
In Visual Studio 2017, version 15.9, the compiler raises C5050 whenever the command-
line options for modules aren't consistent between the module creation and module
consumption sides. In the following example, there are two issues:
The C++ version is /std:c++17 on the creation side, and /std:c++14 on the
consumption side.
Output
The compiler also raises C7536 whenever the .ifc file has been tampered with. The
header of the module interface contains an SHA2 hash of the contents below it. On
import, the .ifc file is hashed, then checked against the hash provided in the header. If
these don't match, error C7536 is raised:
Output
C++
#include <utility>
using size_t = std::size_t;
template <typename T>
struct A {};
template <size_t, size_t>
struct AlignedBuffer {};
template <size_t len>
using AlignedStorage = AlignedBuffer<len, 4>;
struct Alloc
{
static constexpr size_t size = 10;
};
int main()
{
A<void> a;
AlignedStorage<Alloc::size> buf;
if (f<Alloc>(a, buf) != 2)
{
return 1;
}
return 0;
}
Output
As a workaround, we recommended that you not rely on partial ordering to resolve this
problem. Instead, use SFINAE to remove particular overloads. In the following example,
we use a helper class IsA to remove the first overload when Alloc is a specialization of
A:
C++
#include <utility>
using size_t = std::size_t;
struct Alloc
{
static constexpr size_t size = 10;
};
int main()
{
A<void> a;
AlignedStorage<Alloc::size> buf;
if (f<Alloc>(a, buf) != 2)
{
return 1;
}
return 0;
}
In previous versions of Visual Studio, the following code compiles without warning:
C++
void g();
template<typename T>
struct S
{
constexpr void f();
};
template<>
constexpr void S<int>::f()
{
g(); // C3615 in 15.9
}
In Visual Studio 2017 version 15.9, the code raises error C3615:
Output
To avoid the error, remove the constexpr qualifier from the explicit instantiation of the
function f() .
See also
Microsoft C/C++ language conformance
Microsoft C/C++ language conformance
by Visual Studio version
Article • 03/02/2023
Standards conformance for the Microsoft C/C++ compiler in Visual Studio (MSVC) is a
work in progress. Here's a summary of ISO Standard C and C++ language and library
conformance by Visual Studio version. Each C++ compiler and standard library feature
name has a link to the ISO Standard C++ proposal paper that describes the feature,
when one is available at publication time. The Supported column lists the Visual Studio
version in which support for the feature first appeared.
7 Note
There are no binary breaking changes between Visual Studio 2015, 2017, 2019, and
2022. For more information, see C++ binary compatibility between Visual Studio
versions
Feature Supported
P0846R0 ADL and function templates that are not VS 2019 16.1 20
visible
P0306R4 Adding __VA_OPT__ for comma omission VS 2019 16.5. To provide better backward
and comma deletion compatibility, __VA_OPT__ is enabled under
/Zc:preprocessor across all language
versions.
constant expressions
P1938R3 if consteval no
ノ Expand table
Feature Supported
P0433R2 Integrating template deduction for class templates into the VS 2017 15.7
standard library
P0739R0 Improving class template argument deduction integration into
the standard library
P0458R2 contains() For Ordered And Unordered Associative Containers VS 2019 16.1 20
P0482R6 char8_t: A type for UTF-8 characters and strings VS 2019 16.2 20
Feature Supported
P2116R0 Remove tuple-like protocol support from fixed-extent span VS 2019 16.7 20
P0528R3 Library support for atomic compare-and-exchange with padding VS 2019 16.8 20
bits
P1123R0 Editorial Guidance for merging P0019r8 and P0528r3 VS 2019 16.8 20
P0768R1 Library Support For The Spaceship Comparison Operator <=> VS 2019 16.9 20
P2325R3 Views Should Not Be Required To Be Default Constructible VS 2022 17.0 20abi
P2328R1 join_view should join all views of ranges VS 2022 17.0 20abi
P2367R0 Remove misuses of list-initialization from clause 24 ranges VS 2022 17.0 20abi
P2259R1 Partial LWG issue resolution: repairing Input Range Adaptors and VS 2022 17.0 23
counted_iterator
P1425R4 Iterator Pair Constructors For stack And queue VS 2022 17.1 23
P1951R1 Default Template Arguments For pair's Forwarding Constructor VS 2022 17.0 23
P2166R1 Prohibit basic_string and basic_string_view from being VS 2022 17.0 23, R
constructed from nullptr
A group of papers listed together indicates a Standard feature along with one or more
approved improvements or expansions. These features are implemented together.
Feature Supported
aligned_alloc No M
Supported values
No Not yet implemented.
Partial The implementation is incomplete. For more information, see the Notes section.
VS 2010 Supported in Visual Studio 2010.
VS 2013 Supported in Visual Studio 2013.
VS 2015 Supported in Visual Studio 2015 (RTW).
VS 2015.2 and VS 2015.3 indicate features that are supported in Visual Studio 2015
Update 2 and Visual Studio 2015 Update 3, respectively.
VS 2017 15.0 Supported in Visual Studio 2017 version 15.0 (RTW).
VS 2017 15.3 Supported in Visual Studio 2017 version 15.3.
VS 2017 15.5 Supported in Visual Studio 2017 version 15.5.
VS 2017 15.7 Supported in Visual Studio 2017 version 15.7.
VS 2019 16.0 Supported in Visual Studio 2019 version 16.0 (RTW).
VS 2019 16.1 Supported in Visual Studio 2019 version 16.1.
VS 2019 16.2 Supported in Visual Studio 2019 version 16.2.
VS 2019 16.3 Supported in Visual Studio 2019 version 16.3.
VS 2019 16.4 Supported in Visual Studio 2019 version 16.4.
VS 2019 16.5 Supported in Visual Studio 2019 version 16.5.
VS 2019 16.6 Supported in Visual Studio 2019 version 16.6.
VS 2019 16.7 Supported in Visual Studio 2019 version 16.7.
VS 2019 16.8 Supported in Visual Studio 2019 version 16.8.
VS 2019 16.9 Supported in Visual Studio 2019 version 16.9.
VS 2019 16.10 Supported in Visual Studio 2019 version 16.10.
VS 2022 17.0 Supported in Visual Studio 2022 version 17.0.
VS 2022 17.1 Supported in Visual Studio 2022 version 17.1.
VS 2022 17.2 Supported in Visual Studio 2022 version 17.2.
VS 2022 17.3 Supported in Visual Studio 2022 version 17.3.
VS 2022 17.4 Supported in Visual Studio 2022 version 17.4.
VS 2022 17.5 Supported in Visual Studio 2022 version 17.5.
Notes
A In /std:c++14 mode, dynamic exception specifications remain unimplemented, and
throw() is still treated as a synonym for __declspec(nothrow) . In C++17, dynamic
exception specifications were mostly removed by P0003R5, except for one vestige:
throw() is deprecated and required to behave as a synonym for noexcept . In /std:c++17
mode, MSVC now conforms to the Standard by giving throw() the same behavior as
noexcept , that is, enforcement via termination.
To help with migrating code in response to these changes in the Standard and the
Microsoft implementation, new compiler warnings for exception specification issues are
added under /std:c++17 and /permissive-.
B Supported in /permissive- mode in Visual Studio 2017 version 15.7. For more
information, see Two-phase name lookup support comes to MSVC .
C In Visual Studio 2019 version 16.6 and later versions, the compiler fully implements
the standard C99 preprocessor via the /Zc:preprocessor option. (In Visual Studio 2017
versions 15.8 through 16.5, the compiler supports the standard C99 preprocessor via the
/experimental:preprocessor compiler option.) This option is on by default when the
compiler option /std:c11 or /std:c17 is specified.
F Features removed when the /std:c++17 or later compiler option is specified. To re-
enable these features (to ease the transition to newer language modes), use these
macros: _HAS_AUTO_PTR_ETC , _HAS_FUNCTION_ALLOCATOR_SUPPORT ,
_HAS_OLD_IOSTREAMS_MEMBERS , and _HAS_UNEXPECTED .
G C++17's parallel algorithms library is complete. Complete doesn't mean that every
algorithm is parallelized in every case. The most important algorithms have been
parallelized. Execution policy signatures are provided even where the implementation
doesn't parallelize algorithms. The central internal header, <yvals_core.h> , contains the
following "Parallel Algorithms Notes": C++ allows an implementation to implement
parallel algorithms as calls to the serial algorithms. This implementation parallelizes
several common algorithm calls, but not all.
Confusion over user parallelism requirements exists for these algorithms, which are
likely in the above category anyway:
generate , generate_n
These algorithms haven't been evaluated yet. The library might implement
parallelism in a future release:
copy_if , includes , inplace_merge , lexicographical_compare , max_element ,
J std::byte is enabled by /std:c++17 or later, but because it can conflict with the
Windows SDK headers in some cases, it has a fine-grained opt-out macro. To disable it,
define _HAS_STD_BYTE as 0 .
K MSVC doesn't support the _Complex keyword or native complex types. The Universal
CRT <complex.h> uses implementation-specific macros to achieve the same effect. For
more information, see C complex math support.
L The Universal CRT doesn't implement the strftime E and O alternative conversion
modifiers. These modifiers are ignored (for example, %Oe behaves the same as %e ). The
modifiers aren't supported by the underlying locale APIs.
M The Universal CRT doesn't implement C11 aligned_alloc , but does provide
_aligned_malloc and _aligned_free. Because the Windows operating system doesn't
support aligned allocations, this function is unlikely to be implemented.
N The declaration is removed, but the export for the function remains for backward
compatibility.
P Support was added in Visual Studio 2019 version 16.10. Support for Clang was added
in Visual Studio 2022 version 17.0.
14 These C++17 and C++20 features are always enabled, even when /std:c++14 (the
default) is specified. The reason is either because the feature was implemented before
the introduction of the /std options, or because conditional implementation was
undesirably complex.
20 In versions through Visual Studio 2019 version 16.10, these features are enabled by
the /std:c++latest compiler option. Visual Studio 2019 version 16.11 added the
/std:c++20 compiler option to enable these features.
20abi Because of ongoing post-release work on the C++20 standard, <format> , the
formatting parts of <chrono> (which rely on <format> ), and the range factories and
range adaptors from <ranges> (everything that needs the view concept) are only
available under /std:c++latest . Expect these features under /std:c++20 after
agreement is reached with WG21 that no further ABI-breaking changes are necessary.
The remaining parts of <chrono> and the algorithms that apply to ranges are enabled
under the /std:c++20 compiler option in Visual Studio 2019 version 16.11 and later
versions.
23 In Visual Studio 2022 version 17.0 and up, these features are enabled by the
/std:c++latest compiler option.
C11 Compiler support for C11 and C17 requires Visual Studio 2019 version 16.8 or
higher. Except as noted, C11 and C17 library support requires Windows SDK build
10.0.20211.0 or higher. For more information on how to install support for C11 and C17,
see Install C11 and C17 support in Visual Studio.
DR These features are enabled in all C++ /std compiler option modes. The C++
Standard committee adopted this change as a retroactive Defect Report to C++11 and
all later versions.
2104 C11 library support for this feature requires Windows SDK build 10.0.20348.0
(version 2104) or higher.
See also
C++ Language Reference
C++ Standard Library
C++ conformance improvements in Visual Studio
What's New for Visual C++ in Visual Studio
Visual C++ change history 2003 through 2015
Visual C++ What's New 2003 through 2015
C++ team blog
Feedback
Was this page helpful? Yes No
Windows XP b X X
Windows Vista X X
Windows 7 X X
Windows 8 X X X
Windows 8.1 X X X
Windows 10 X X X X
Windows 11 X X X X
Android c X X X X
iOS c X X X X
Linux d X X X X
c You can install the Mobile development with C++ workload in the installer for Visual
Studio 2017 and later. In Visual Studio 2015 setup, choose the optional Visual C++ for
Cross Platform Mobile Development component to target iOS or Android platforms.
For instructions, see Install Visual C++ for Cross-Platform Mobile Development. To build
iOS code, you must have a Mac computer and meet other requirements. For a list of
prerequisites and installation instructions, see Install And Configure Tools to Build using
iOS. You can build x86 or ARM code to match the target hardware. Use x86
configurations to build for some Android devices. Use ARM configurations to build for
iOS devices and most Android devices.
d
You can install the Linux development with C++ workload in the installer for Visual
Studio 2017 and later to target Linux platforms. For instructions, see Download, install,
and setup the Linux Workload. This toolset compiles your executable on the target
machine, so you can build for any supported architecture.
For information about how to set the target platform configuration, see How to:
Configure Visual C++ projects to target 64-bit, x64 platforms.
See also
Visual C++ tools and features in Visual Studio editions
Getting Started
Microsoft Visual C++ compiler
versioning
Article • 02/16/2024
_MSC_VER = MMNN
_MSC_FULL_VER = MMNNBBBBB
_MSC_BUILD = R
For example, the compiler version for Visual Studio 2022 version 17.9.0 is 19.39.33519:
_MSC_VER = 1939
_MSC_FULL_VER = 193933519
7 Note
Visual Studio 2019 16.8 and 16.9 share the same major and minor versions, and so
have the same value for _MSC_VER . As do Visual Studio 2019 16.10 and 16.11. To
distinguish them, use _MSC_FULL_VER as described in Service releases starting with
Visual Studio 2017.
7 Note
For example, two cases where _MSC_FULL_VER is useful is to distinguish Visual Studio
2019 16.8 from 16.9, and Visual Studio 2019 16.10 from 16.11. That's because those
versions share the same major and minor versions, and so have the same value for
_MSC_VER .
Version macros
Recall that the version number consists of four fields:
_MSC_FULL_VER represents the major, minor, and build version of the compiler. It has
the form: MMNNBBBBB. Use it to distinguish between different versions of the compiler,
including servicing releases. See Service releases starting with Visual Studio 2017 for
more information about Visual Studio 2019 16.8, 16.9, 16.10 and 16.11.
_MSC_BUILD represents the build version of the compiler. It has the form: R. Use it to
distinguish between servicing releases.
When the major version changed between Visual Studio 2013 and Visual Studio 2015,
_MSC_VER reflected the change by going from 1800 to 1900.
An example of a minor change is from Visual Studio 2022 17.1 to Visual Studio 2022
17.2. In that case, _MSC_VER changed from 1931 to 1932.
The following table lists the Visual C++ compiler _MSC_VER for each Visual Studio
release:
ノ Expand table
a
Visual Studio 2019 16.8 and 16.9 share the same major and minor versions (and so
have the same value for _MSC_VER ). To distinguish them, use _MSC_FULL_VER . The
minimum value of _MSC_FULL_VER for Visual Studio 2019 16.8 is 192829333. The
minimum value of _MSC_FULL_VER for Visual Studio 2019 16.9 is 192829910.
b
Visual Studio 2019 16.10 and 16.11 share the same major and minor versions (and so
have the same value for _MSC_VER ). To distinguish them, use _MSC_FULL_VER . The
minimum value of _MSC_FULL_VER for Visual Studio 2019 16.10 is 192929917. The
minimum value of _MSC_FULL_VER for Visual Studio 2019 16.11 is 192930129.
See also
_MSC_VER
Visual C++ compiler version blog post
C++ Tools and Features in Visual Studio
Editions
Article • 12/01/2021
The following C++ features are available in Visual Studio. Unless stated otherwise, all
features are available in all editions: Visual Studio Community, Visual Studio
Professional, and Visual Studio Enterprise. Some features require specific workloads or
optional components, which you can install with the Visual Studio Installer.
Platforms
Windows Desktop
Universal Windows Platform ((tablet, PC, Xbox, IoT, and HoloLens))
Linux
Android
iOS
Compilers
MSVC 32-bit compiler for x86, x64, ARM, and ARM64
MSVC 64-bit compiler for x86, x64, ARM, and ARM64
GCC cross-compiler for ARM
Clang/LLVM
On Windows, Clang/LLVM 12.0, targeting x86 or x64 (CMake support only).
On Linux, any Clang/LLVM installation supported by the distro.
C++ Workloads
Visual Studio includes the following workloads for C++ development. You can install any
or all of these, along with other workloads such as .NET Desktop Development, Python
Development, Azure Development, Visual Studio Extension Development, and others.
Optional Components:
Optional Components:
IntelliCode
IntelliTrace (Enterprise only)
USB Device Connectivity
C++ (v143) Universal Windows Platform tools
C++ (v142) Universal Windows Platform tools
C++ (v141) Universal Windows Platform tools
Graphics debugger and GPU profiler for DirectX
Windows 11 SDK
Windows 10 SDK (other versions)
Architecture and analysis tools
Optional Components:
Optional Components:
Individual components
You can install these components independently from any workload.
JavaScript diagnostics
Live Share
C++ Universal Windows Platform runtime for v142 build tools
ClickOnce Publishing
Microsoft Visual Studio Installer Projects
Windows SDK
Project Templates
The following project templates are available depending on which workloads you have
installed.
Windows Desktop:
Empty Project
Console App
Windows Desktop Wizard
Windows Desktop Application
Shared Items Project
MFC App
Dynamic Link Library
CLR Empty Project
CLR Console App
Static Library
CMake Project
ATL Project
MFC Dynamic Link Library
CLR Class Library
Makefile Project (Windows)
MFC ActiveXControl
Native Unit Test Project
Google Test
Blank App
DirectX 11 and XAML App
DirectX 11 App
DirectX 12 App
Unit Test App
DLL
Windows Runtime Component
Static Library
Windows Application Packaging Project
Linux:
Tools
Incremental Linker (Link.exe)
Microsoft Makefile Utility (Nmake.exe)
Lib Generator (Lib.exe)
Windows Resource Compiler (Rc.exe)
Windows Resource to Object Converter (CvtRes.exe)
Browse Information Maintenance Utility (BscMake.exe)
C++ Name Undecorator (Undname.exe)
COFF/PE Dumper (Dumpbin.exe)
COFF/PE Editor (Editbin.exe)
MASM (Ml.exe)
Spy++
ErrLook
AtlTrace
Inference Rules
Profile Guided Optimizations
Debugging Features
Native Debugging
natvis (native type visualization)
Graphics Debugging
Managed Debugging
GPU usage
Memory usage
Remote Debugging
SQL Debugging
Static Code Analysis
Designers and Editors
XAML Designer
CSS Style Designer/Editor
HTML Designer/Editor
XML Editor
Source Code Editor
Productivity Features: Refactoring, EDG IntelliSense engine, C++ Code Formatting
Windows Forms Designer
Data Designer
Native Resource Editor (.rc files)
Resource Editors
Model editor
Shader designer
Live Dependency Validation (Enterprise Only)
Architectural Layer Diagrams (Enterprise Only)
Architecture Validation (Enterprise Only)
Code Clone (Enterprise Only)
Data Features
Data Designer
Data Objects
Web Services
Server Explorer
See also
Install Visual Studio
What's New in Visual Studio
C++ project types in Visual Studio
Install C11 and C17 support in Visual
Studio
Article • 10/29/2021
Support for C11 and C17 standards is available in Visual Studio 2019 version 16.8 and
later. Support requires an updated Universal C Runtime (UCRT) and Windows SDK
version to work properly with the conforming preprocessor (/Zc:preprocessor).
Windows SDK releases correspond with Windows OS releases. C11 and C17 support
requires Windows SDK 10.0.20348.0 (version 2104) or later. The Windows SDK is an
installable option in the Individual Components tab in the Visual Studio Installer. You
can follow these steps to set up the latest SDK and build C11 or C17 code in Visual
Studio or at the command line.
Prerequisites
Visual Studio 2019 version 16.8 or later and Windows SDK 10.0.20348.0 (version 2104) or
later installed and running on your computer. We recommend you use the latest version
available for the best support.
If Visual Studio isn't installed yet, see Install C++ support in Visual Studio for
installation instructions. In the install, include the Desktop development with C++
workload. Then, open the Individual Components tab. Select Windows 10 SDK
(10.0.20348.0) or later, or the latest Windows 11 SDK.
If Visual Studio is already installed, but you don't have the required Windows SDK,
open the Visual Studio Installer. Choose Modify next to your version of Visual
Studio to install the selected components. Open the Individual Components tab.
Select Windows 10 SDK (10.0.20348.0) or later, or the latest Windows 11 SDK.
Choose Modify to install the selected components.
Set the project to use the Windows SDK you just installed. On the Configuration
Properties > General page, set the Windows SDK Version property either to 10.0 (latest
installed version), or to the specific SDK version you installed.
You'll also see a C-specific option: C Language Standard. Set this property to ISO C11
Standard ( /std:c11 ) or ISO C17 (2018) Standard ( /std:c17 ).
The C++ Language Standard property is used when the language is C++. It's the default
when the file extension is .cpp . The C Language Standard property version is used when
the language is C. It's the default when the file extension is .c . To build using C11 or
C17, put your source code in a .c file, or set the code to compile as C. You can set this
property for your project on the Configuration Properties > C/C++ > Advanced page.
Set the Compile As property to Compile as C code (/TC).
Congratulations, you've set up everything you need to build C11 and C17 code in Visual
Studio!
See also
/std (Specify language standard version)
Visual Studio C++ Samples
Article • 08/30/2022
Samples for Visual Studio C++ are available on the web. Microsoft has produced many
C++ samples that demonstrate different functionalities across multiple technologies.
Here are a few of the places to find additional samples:
) Important
This sample code is intended to illustrate a concept, and it shows only the code
that is relevant to that concept. It may not meet the security requirements for a
specific environment, and it should not be used exactly as shown. We recommend
that you add security and error-handling code to make your projects more secure
and robust. Microsoft provides this sample code "AS IS" with no warranties.
ATL samples
ノ Expand table
Sample name Description
ATLButton Creates a button that displays itself with three different bitmaps depending on
its state.
ATLSecurity Shows how to use the ATL security classes to examine security settings.
CThreadPool Shows how to use a thread pool in an application and how implementing a
thread pool can improve the application's performance.
MFCATL Illustrates how ATL COM objects can be used in an MFC server EXE.
ノ Expand table
Sample Description
name
CDInfo Plays CD audio tracks and displays information about the tracks in tooltips and a
pie chart display.
Circ Creates a control that demonstrates property pages and draws a circle.
Polygon Builds a control that implements custom properties, events, property pages, and
object safety.
ATLSafeArray Shows how to create and maintain SAFEARRAY s using CComSafeArray ; also how
to pass SAFEARRAY s from a component to script.
COMMap Demonstrates COM interface map entry macros with compiler COM support.
CustomString Shows how to use a custom memory allocator for CStringT to improve
performance in a multithreaded application.
ノ Expand table
CatDB Displays the schema information, such as tables and columns, of OLE DB
providers.
DynamicConsumer Demonstrates using dynamic accessor and schema rowset classes to read
metadata from a database.
ノ Expand table
Sample name Description
BirthdayPicker Shows how the .NET Framework resource mechanism can be used in C++
applications. It also demonstrates some common Window Forms
components.
Calculator Implements a simple pocket calculator using C++ and the .NET
Framework Windows Forms classes.
Scribble (using MFC) An MFC implementation of the Scribble sample, updated and extended to
include new .NET functionality.
Scribble (Windows A Windows Forms implementation of the Scribble sample, updated and
Forms) extended to include new .NET functionality.
STLCLR Demonstrates some of the capabilities available when using the STL/CLR
Library.
ComTypeLibfor7 samples
ノ Expand table
Sample Description
name
AllInOne Implements a server using ATL, exposing STL collections, and controlled by
compiler COM support in an MFC application.
COMMap Demonstrates COM interface map entry macros with compiler COM support.
DCOM Demonstrates how to call a COM object (implemented in a Windows service) from
multiple clients, running on different computers.
FreeThrd Demonstrates a multithreaded client and free-threaded server with compiler COM
support.
Labrador Implements an EXE server that doesn't have any user interface.
Compiler samples
ノ Expand table
Sample Description
name
ccWrapper Demonstrates how to map C/C++ compiler flags from other compilers to the
Visual C++ compiler (cl.exe).
ノ Expand table
Sample name Description
EuclidStep1 A pure C project that demonstrates Euclid's algorithm for finding the greatest
common divisor.
EuclidStep2 An extension of EuclidStep1 that is a mixed C and MASM project. The core of
Euclid's algorithm is moved from the .c file to an .asm file, with the .c file
calling into the .asm file.
PrimesStep1 A pure C project that demonstrates the Sieve of Eratosthenes to find prime
numbers.
PrimesStep2 An extension of PrimesStep1 that is a mixed C and MASM project that moves the
core algorithm to the .asm file.
PrimesStep3 An extension of PrimesStep2 that adds a separate C header file and an .asm
include file to declare the extern function and global data structure.
CRT samples
ノ Expand table
Sample Description
name
SecureCRT This sample demonstrates how to upgrade code that used deprecated CRT
functions to increase code security.
Debugging samples
ノ Expand table
Sample Description
name
EEAddIn Uses the Expression Evaluator Add-In API to extend the native debugger
expression evaluator.
Fusion samples
ノ Expand table
Sample Description
name
Hilo sample
ノ Expand table
Sample Description
name
Hilo Hilo is a series of articles and sample applications. They demonstrate the power of
Windows 7, Visual Studio and C++ to build high performance, responsive client
applications. Hilo provides both source code and guidance that will help you design
and develop compelling, touch-enabled Windows applications of your own.
This sample has been updated for Visual Studio 2013. It includes a hot fix to the
AsyncLoaderMemoryManager.cpp file (in lines 36 and 37), which addresses a common
crash issue.
International samples
ノ Expand table
Sample Description
name
IME Demonstrates how to control the Input Method Editor mode and how to
implement IME level 3.
Sample Description
name
Sample Description
name
MEDriver Illustrates the use of COM events (fired from an unmanaged COM server) through
a .NET Framework wrapper, automatically generated from the COM server's type
library.
QStat Shows how to create a DLL that wraps access to a COM object and exposes its
functionality to .NET Framework clients.
Scribble Demonstrates how to develop a Windows Forms MDI application using C++/CLI
and the .NET Framework classes.
MFC samples
ノ Expand table
Cube OpenGL application using MFC device contexts along with OpenGL's resource
contexts.
Sample name Description
DLLHusk Sharing the DLL version of the Foundation class library with an application and
custom DLL.
DLLScreenCap A regular DLL that can be statically or dynamically linked to the Microsoft
Foundation Class Library.
MTGDI Demonstration of sharing GDI resources among multiple threads using the
framework's single document interface (SDI) support for documents and views.
Mutexes Dialog-based application that creates two CWinThread objects and uses them
to do a task under the user's control.
ノ Expand table
Sample Description
name
Button Demonstrates use of an in-place active menu, a stock property page, and the
About box control option.
Circ Demonstrates ActiveX control basics. These include control painting, stock and
custom properties, stock and custom events, use of colors and fonts, the stock Font
property page, the default property page, and versioning.
CmnCtrl Demonstrates some of the new controls available with MFC on wiprlhext: The
command link button ( CButton ), the pager control ( CPagerCtrl ), the split button
( CSplitButton ), and the network address control ( CNetAddressCtrl ).
Image Demonstrates how to use MFC to build an ActiveX control that downloads data
asynchronously.
Localize A control with a localized user interface that demonstrates use of separate type
libraries and resource dynamic-link libraries (DLLs) for localization.
NetAddr Demonstrates use of the Windows Vista "Net Address Verifier" control.
Sample Description
name
Pal Control that displays the colors of a palette. It demonstrates read-only properties,
persistent Get/Set properties, persistent parameterized properties, and picture
properties.
SpinDial A control with the visual appearance of a spin-dial that demonstrates property
page data validation.
TestHelp An ActiveX control that has its own help file and tooltips.
Time A control that is invisible at run time and fires a timer event at set intervals.
Demonstrates notification functions and ambient properties.
XList A control, subclassed from a Windows list box, that displays text or bitmap items.
ノ Expand table
ClipArt The ClipArt directory contains sample resources that you can use to customize
the appearance of your application.
CmnCtrl1 Demonstrates how to create and change the styles of Windows Common
Controls using MFC classes (Part 1).
CmnCtrl2 Demonstrates how to create and change the styles of Windows Common
Controls using MFC classes (Part 2).
CtrlBars Custom toolbar and status bar, dialog bar, and floating palette.
CtrlTest Owner-draw list box and menu, custom control, bitmap button, spin control.
DBVList Uses the CListView and CDaoRecordset classes to implement the virtual list
view functionality available for the list view common control.
Dynamenu Dynamically modifying list of items in menus; handling commands not known
at compile time; and updating the status bar command prompt for such
commands.
FileDlgWatcher Creates a custom dialog box that illustrates what events are generated when
you create a CFileDialog .
Hello Illustrates a single application window with a menu and About box.
HelloApp Minimal MFC sample that illustrates that few lines of code are required to get
a window to appear on the screen.
ListHdr Demonstrates how to use the common control MFC classes CListCtrl and
CHeaderCtrl .
MDIDocVw Updated version of the MDI sample that uses the document/view
architecture.
MMXSwarm Demonstrates how to use CImage , the __m64 data type, and device-
independent bitmaps (DIBs).
Modeless Demonstrates the use of an MFC CDialog object as a modeless dialog box.
Multipad Simple text editor that lets the user open and edit multiple text files at one
time.
SnapVw Shows how to use property pages in an MDI child frame window.
Spiro A game that shows to use CImageList and how to use memory display
contexts in applications requiring animation effects.
ノ Expand table
Scheduler Demonstrates how to create an HTML-based dialog box using the Visual C++
libraries classes.
ノ Expand table
Sample Description
name
InProc An in-process Automation server that can be loaded as a DLL in the client's
address space.
IPDrive A simple Automation client application that drives the INPROC sample application.
OClient ActiveX Visual Editing container application, with drag and drop.
SuperPad Demonstrates a visual editing server that edits text using CEditView.
TstCon Implements an ActiveX control container using MFC's support for OLE embedding.
You can use TSTCON to test ActiveX controls, change their properties, and invoke
their methods.
WordPad Uses MFC's support for rich edit controls to create a basic word processor.
ノ Expand table
Sample Description
name
GUIDGen A simple dialog-based MFC application that generates globally unique identifiers.
ノ Expand table
MDITabsDemo Demonstrates how to create an application that uses the new tabbed
MDI documents interface instead of the traditional MDI child
windows.
PropSheetDemo Illustrates the following types of Property Sheet control: simple, with
tabs at the left side, with tree control at the left side, OneNote-style
tabs, list of items at the left side.
RibbonGadgets Illustrates various controls that can be hosted in the Ribbon Control.
At the bottom of the main frame, you can find the Source Code
window with source code text, which outlines how to create a
particular gadget.
TabControl Demonstrates the MFC Tab Control and the different appearances it
has using different properties and visual managers.
TasksPane Demonstrates the MFC Task Pane classes and their different
appearances using various properties and visual managers.
TrayMenu Illustrates the ability to use MFC Control Bar menus with the system
tray icon. It's similar to the notification icons in the lower-right corner
of the display.
ノ Expand table
GestureDemo Demonstrates the Windows Touch support in MFC (requires touch hardware).
TouchDemo Demonstrates the Windows Touch support in MFC (requires touch hardware).
ODBC samples
ノ Expand table
Sample Description
name
odbcsql This sample demonstrates how to use ODBC APIs to Connect to and access
database.
OS samples
ノ Expand table
Sample Description
name
Unix samples
ノ Expand table
Sample name Description
Unix - Demonstrates a wrapper that maps flags from the Sun Forte and gcc
ccWrapper compilers to the Microsoft Visual C++ compiler (cl.exe).
Windows 8 samples
The Windows 8 Sample Pack includes all the app code examples developed and
updated for Windows 8. The sample pack provides a convenient way to download all
the samples at once. The samples in this sample pack are available in C#, C++, VB.NET,
and JavaScript. The Windows Samples Gallery contains code samples that exercise the
various new programming models, platforms, features, and components available in
Windows 8 and Windows Server 2012. These downloadable samples contain the Visual
Studio solution (sln) file, source files, assets, resources, and metadata necessary to
compile and run successfully.
ノ Expand table
CryptoWinRT sample This sample shows how to use the new Cryptography APIs.
(Windows 8)
Print sample (Windows 8) This sample demonstrates how apps can integrate the Windows
print experience. The scenarios demonstrated in this sample
include: Printing from the app by using the charms bar and the print
contract, Printing from within the app experience, and more.
HttpClient sample This sample demonstrates the use of the HttpClient class and the
(Windows 8) IXMLHTTPRequest2 interface to upload and download various types
of content from an HTTP server using the networking features
provided by the Windows Runtime.
Account picture name This sample demonstrates different ways of getting the name of the
sample (Windows 8) user that is currently logged in. It also demonstrates how to get and
set the image used for the user's tile.
App settings sample This sample demonstrates how to use the ApplicationSettings API
(Windows 8) and settings flyouts to integrate an app's settings UI with the
Settings charm. The sample uses the
Windows.UI.ApplicationSettings namespace and
WinJS.UI.SettingsFlyout .
Windows Store device app This sample demonstrates how to create a Windows Store device
for camera sample app for a camera. A Windows Store device app is provided by an
(Windows 8) IHV or OEM to differentiate the capture experience for a particular
camera.
Getting started with C++ The sample demonstrates some basic principles of Windows Store
simple blog reader sample app development in native C++ using XAML to define the user
(Windows 8) interface. It's a complete working version of the application
discussed on the Windows Developer Center.
Reading and writing data This sample shows how to use the DataReader and DataWriter
sample (Windows 8) classes to store and retrieve data.
Application data sample This sample shows you how to store and retrieve data that is
(Windows 8) specific to each user and Windows Store app using the Windows
Runtime application data APIs. Application data includes session
state, user preferences, and other settings.
Custom driver access This sample shows how to use CreateDeviceAccessInstance and
sample (Windows 8) IDeviceIoControl to access a specialized device.
XAML ListView and This sample demonstrates how to use the GridView and ListView
GridView essentials sample controls.
(Windows 8)
Animation metrics sample This sample shows how to use the Animation Metrics APIs in
(Windows 8) Windows.UI.Core.AnimationMetrics to access the raw parameters
that define the animations in the Windows Animation Library.
XAML DirectX 3D shooting This sample demonstrates the implementation of a simple first
game sample (Windows 8) person 3-D game using DirectX (Direct3D 11.1, Direct2D, XInput,
and XAudio2) and XAML in a C++ app. XAML is used for the heads-
up display and game state messages.
Sample name Description
XAML scrolling, panning, This sample demonstrates how to use the ScrollViewer control to
and zooming sample pan and zoom.
(Windows 8)
XAML FlipView control This sample demonstrates how to use the FlipView control to
sample (Windows 8) enable users to flip through a collection.
Device app for printers This sample shows how to create a device app for printers that can
SDK sample (Windows 8) be activated from the tile contract, the printTaskSettings contract,
and from toast displayed by backgroundTask in response to print
driver event.
Background task sample This sample shows you how to create and register background tasks
(Windows 8) using the Windows Runtime background task API. A background
task is triggered by a system or time event, and can be constrained
by one or more conditions.
StreamSocket sample This sample demonstrates the basics of the StreamSocket class
(Windows 8) using the networking features provided by the Windows Runtime.
The client component of the sample creates a TCP socket to make a
network connection, uses the socket to send data, and more.
Scheduled notifications This sample shows how to use scheduled and recurring tile updates
sample (Windows 8) and toast notifications for an app. This ability enables you to specify
a precise time to deliver the notification, even if the app isn't
running.
File access sample This sample shows how to create, read, write, copy and delete a file,
(Windows 8) how to retrieve file properties, and how to track a file or folder so
that your app can access it again. This sample uses Windows.Storage
and Windows.Storage.AccessCache API.
Removable storage sample The removable storage sample demonstrates how to transfer files
(Windows 8) to and from removable storage devices. This sample requires a
Sample name Description
Configure keys for media This sample demonstrates how to configure the hardware media
sample (Windows 8) keys on a keyboard. Then, how to use the configured keys to
control an audio-video stream by pressing or clicking play, pause,
stop, and so on.
XAML personality This sample demonstrates how to use the built-in personality
animations sample animations in your app.
(Windows 8)
Toast notifications sample This sample shows how to use toast notifications: Ones that appear
(Windows 8) as pop-up notifications in the upper right corner of the screen. A
user can select the toast (touch or click) to launch the associated
app.
Contact Picker app sample This sample demonstrates how to use the Contact Picker to select
(Windows 8) one or more contacts. It also includes a basic implementation of the
Contact Picker APIs to demonstrate how to display a list of contacts
to the user.
DirectX marble maze game This sample demonstrates how to build a basic 3D game using
sample (Windows 8) DirectX. This game is a simple labyrinth game where the player is
challenged to roll a marble through a maze of pitfalls using tilt
controls.
DirectX postcard app This sample demonstrates the implementation of a simple Windows
sample (Windows 8) Store app using DirectX with C++ for postcard creation using
DirectX and XAML interop.
DirectX 3D shooting game This sample demonstrates the implementation of a simple first
sample (Windows 8) person 3-D game using DirectX (Direct3D 11.1, Direct2D, XInput,
and XAudio2) in a C++ app.
XAML AppBar control This sample demonstrates how to use the AppBar control to present
sample (Windows 8) navigation, commands, and tools to users. The app bar is hidden by
default and appears when users swipe a finger from the top or
bottom edge of the screen.
Sample name Description
Date and time formatting This sample demonstrates how to use the DateTimeFormatter class
sample (Windows 8) in the Windows.Globalization.DateTimeFormatting namespace to
display dates and times according to the user's preferences.
Secondary tiles sample This sample shows how to pin and use a secondary tile. That's a tile
(Windows 8) that directly accesses a specific, non-default section or experience
within an app, such as a saved game, or a specific friend in a social
networking app.
Input Touch hit testing This sample uses a polygon shapes puzzle to demonstrate how to
sample (Windows 8) handle pointer input, implement custom hit testing for touch input,
and process manipulations in a Windows Store app using C++ and
DirectX.
Network information This sample demonstrates how to use the Windows Runtime
sample (Windows 8) Network Information APIs.
Input Simplified ink sample This sample demonstrates how to use ink functionality in Windows
(Windows 8) Store apps.
StorageDataSource and This sample shows how to retrieve and display images in the user's
GetVirtualizedFilesVector Pictures Library.
sample (Windows 8)
Edge-based gesture This sample shows how to listen for events that occur in edge-
invocation sample based UI, using the EdgeGesture class.
(Windows 8)
Application resources and This sample shows how to use application resources to separate
localization sample localizable content from application code. The sample uses the
(Windows 8) Windows.ApplicationModel.Resources.Core and
Windows.Globalization namespaces, and WinJS.Resources .
Context menu sample This sample shows how to create a context menu and how to
(Windows 8) replace the default context menu for text. This sample uses
Windows.UI.Popups API, including the PopupMenu and the
oncontextmenu event.
Geolocation sample The Geolocation sample demonstrates how to use the Geolocation
(Windows 8) API to get the geographic location of the user's PC. An app can use
the Geolocation API to get location one time, or it can continuously
track the location.
Message dialog sample This sample demonstrates how to use a MessageDialog for
(Windows 8) displaying dialogs, setting commands and their actions, and
Sample name Description
MediaStreamSource media This sample shows how to support the Microsoft Silverlight
extension sample MediaStreamSource concept in a Windows Store app.
(Windows 8)
DirectWrite vertical text This sample uses DirectWrite and Direct2D to properly display
sample (Windows 8) vertical text in a custom layout shape.
Direct2D custom image This sample demonstrates how to implement custom Direct2D
effects sample (Windows 8) Effects using standard pixel, vertex, and compute shaders.
DirectX touch input sample This sample demonstrates touch and mouse navigation of a 3-D
(Windows 8) environment in a C++ app with Direct3D.
XInput game controller This sample demonstrates the use of the XInput APIs in a C++ app.
sample (Windows 8) It reads input from an Xbox game controller and displays data
about the analog stick movements and button presses.
Direct3D-Direct2D interop This sample shows how to interoperate with Direct2D and
sample (Windows 8) DirectWrite to write text to a Direct3D render target. It's an effective
way to create heads-up displays and text-based readouts such as
scoring panels in games and 3-D apps.
Syndication sample This sample demonstrates a basic Windows Store app for Windows
(Windows 8) 8 that can retrieve feeds from a web service. This sample is currently
provided in the JavaScript, C#, C++, and VB programming
languages.
App tiles and badges This sample shows how to use an app tile, which is the
sample (Windows 8) representation and launch point for your app in the Start screen. It
also shows how to use a badge on that tile. It's a method for the
app to relay status information to the user when the app isn't
running.
XAML user and custom This sample demonstrates how to create and use XAML
controls sample (Windows UserControl elements and create custom controls for your projects.
8)
Direct3D resource loading This sample demonstrates Direct3D resource loading for C++ apps
sample (Windows 8) with DirectX.
XAML ListView and This sample demonstrates the interaction model of the ListView
GridView customizing control.
Sample name Description
interactivity sample
(Windows 8)
XAML WebView control This sample demonstrates how to use the WebView control to
sample (Windows 8) display a URL, load HTML, interact with script within a WebView , and
use WebViewBrush .
Display orientation sample This sample demonstrates how to use the DisplayProperties class
(Windows 8) to set the display orientation in an app.
Direct2D interpolation This sample shows the various interpolation modes used by
modes sample (Windows Direct2D.
8)
Direct2D geometry This sample shows how multi-core geometry tessellation can help
realization sample reduce geometry rendering time. Using opacity masks and meshes
(Windows 8) is an alternative to traditional geometry rendering that may be
better in some situations.
Language font mapping This sample demonstrates how to obtain language-specific font
sample (Windows 8) recommendations using the LanguageFontGroup class in the
Windows.Globalization.Fonts namespace.
XAML high contrast style This sample demonstrates various techniques for implementing
sample (Windows 8) support for high contrast mode in your app. Support for high
contrast mode is important to make your app accessible to people
with eyesight problems.
Input Device capabilities This sample demonstrates how to query the input devices that are
sample (Windows 8) connected to the user's device. And, how to support the pointer,
touch, pen/stylus, mouse, and keyboard input modes of Windows
Store apps.
Sample name Description
EAS policies for mail clients This sample shows how mail clients can retrieved device information
sample (Windows 8) and work with supplied Exchange Active Sync (EAS) policies.
Windows Store apps can configure their mail clients to stay
compliant with the given EAS policies.
DatagramSocket sample This sample demonstrates the basics of the DatagramSocket class
(Windows 8) using the networking features provided by the Windows Runtime.
The client component of the sample creates a UDP socket, uses the
socket to send and receive data, and closes the socket.
DirectWrite hello world This sample shows how to use DirectWrite and Direct2D to render
sample (Windows 8) the text "Hello World" to a CoreWindow .
Compression sample This sample demonstrates how to read structured data from a file
(Windows 8) and write compressed data to a new file and how to read
compressed data and write decompressed data to a new file. Many
applications need to compress and decompress data.
App package information This sample shows you how to get package information using the
sample (Windows 8) Windows Runtime packaging API. Users acquire your Windows
Store app as an app package. Windows uses the information in an
app package to install the app on a per-user basis.
Mobile broadband account This sample demonstrates how to use the Windows 8 Mobile
provisioning sample Broadband provisioning agent API
(Windows 8) ( Windows.Networking.NetworkOperators.ProvisioningAgent ) to
configure Windows 8 with required connectivity information and
access provisioning.
Media Play To sample This sample demonstrates the Play To API. It shows how you can
(Windows 8) expand your media application to stream video, audio, and images
to other devices on your local network.
Input Touch keyboard This sample demonstrates how to launch the touch keyboard
sample (Windows 8) automatically in custom controls that aren't derived from platform
controls. The sample implements custom controls that require
keyboard input and aren't derived from standard XAML controls.
Sample name Description
XAML animation library This sample demonstrates how to animate elements and apply
sample (Windows 8) easing functions to the animations to achieve various effects.
Snap sample (Windows 8) The snapped state is one of the four possible application view
states. Snapping an app resizes the app to 320 pixels wide, which
allows it to share the screen with another app. Snapping enables
two apps to be visible at the same time.
IXmlReader and IXmlWriter This sample demonstrates how to use IXmlReader and IXmlWriter
XML data read write in your Windows Store app with C++. They're used to read and
sample (Windows 8) write XML data from a flat XML-formatted text file. These interfaces
are part of the Windows Win32 and COM APIs, but are supported
by the Windows Runtime.
Media capture using This sample demonstrates how to use the MediaCapture API to
capture device sample capture video, audio, and pictures from a capture device, such as a
(Windows 8) webcam.
XAML Popup sample This sample demonstrates how to create and use the XAML Popup
(Windows 8) element in your projects.
XAudio2 audio file This sample demonstrates the use of XAudio2 in an app.
playback sample (Windows
8)
Hilo C++ sample This sample demonstrates how to build a complete Windows Store
(Windows 8) app using C++ and XAML. The Hilo photo sample provides
guidance to C++ developers that want to create a Windows 8 app
using modern C++, XAML, and the Windows Runtime.
DirectWrite custom text This sample shows how to implement a custom text renderer for
renderer sample (Windows DirectWrite.
8)
Sample name Description
DirectWrite font This sample shows how to use DirectWrite to list the fonts in the
enumeration sample system font collection on a user's device.
(Windows 8)
Direct2D perspective This sample shows how to use the DrawBitmap API to display an
transform sample image with a perspective transform applied to it.
(Windows 8)
CameraOptionsUI Sample This sample demonstrates how to use camera options in a device
(Windows 8) app. The CameraOptionsUI API displays a UI for adjusting camera
settings. This sample requires a webcam.
XInput audio controller This sample demonstrates XAudio2 playback to an XInput device,
playback sample (Windows such as a headset, in an app.
8)
Windows account This sample demonstrates how to use the members of the
authorization sample Windows.Security.Authentication.OnlineId namespace to
(Windows 8) authenticate a user with their Microsoft Account in delegation
mode. And, how to send acquired tokens to Live Connect APIs
using REST protocol.
Number formatting and This sample demonstrates how to use the DecimalFormatter ,
parsing sample (Windows CurrencyFormatter , PercentFormatter , and PermilleFormatter
8) classes in the Windows.Globalization.NumberFormatting namespace.
They're used to display and parse numbers, currencies, and percent
values.
DXGI offer and reclaim This sample demonstrates the use of the DXGI
resources sample IDXGIDevice2::OfferResources and IDXGIDevice2::ReclaimResources
(Windows 8) APIs in a C++ app with DirectX.
Web authentication broker This sample demonstrates the web authentication broker WinRT
sample (Windows 8) API. It lets you enable single sign-on (SSO) connections to OAuth
providers such as Facebook, Google, Microsoft, and Twitter.
XAudio2 audio stream This sample demonstrates audio streaming in a C++ app using the
effect sample (Windows 8) XAudio2 and Media Foundation APIs.
Splash screen sample This sample shows how to imitate the splash screen that Windows
(Windows 8) displays for your app, by positioning a similar image correctly when
Windows dismisses the splash screen that it displays.
SMS background task This sample shows how to use the Windows 8 Mobile Broadband
sample (Windows 8) SMS API ( Windows.Devices.Sms ) with the Background Task API
Sample name Description
SMS message send, This sample shows how to use the Windows 8 Mobile Broadband
receive, and SIM SMS API ( Windows.Devices.Sms ).
management sample
(Windows 8)
Trial app and in-app This sample demonstrates how to use the licensing API provided by
purchase sample (Windows the Windows Store to determine the license status of an app, or of a
8) feature enabled by an in-app purchase.
Input Touch keyboard text This sample shows how to enable optimized views on the touch
input sample (Windows 8) keyboard. It works by using input scopes and input types with
controls in the WinJS.UI namespace, and with the TextBox and
RichEdit XAML controls.
XAML text editing sample This sample demonstrates how to use text input controls in your
(Windows 8) app.
Thread pool sample This sample shows you how to run work items asynchronously using
(Windows 8) the Windows Runtime thread pool API.
XAML accessibility sample This sample shows you how to add basic accessibility support to
(Windows 8) your app.
Playlist sample (Windows This sample demonstrates how to create, save, display, and edit a
8) playlist of audio files. This sample uses classes that are in the
Windows.Media.Playlists namespace.
Media Server client sample This sample demonstrates how to create a Media Server client using
(Windows 8) the Media Server API. The Media Server sample demonstrates how
to browse a Digital Media Server programmatically on your local
network, and display all of its video files.
Direct2D magazine app This sample shows how to use Direct2D, DirectWrite, Windows
sample (Windows 8) Imaging Component (WIC), and XAML to build an app with a
magazine-type presentation.
Mobile broadband account This sample shows how to use the Windows 8 Mobile Broadband
and device management API ( Windows.Networking.NetworkOperators ) employed by Mobile
sample (Windows 8) Network Operators (MNO). It demonstrates how to use the
MobileBroadbandAccount APIs to retrieve and display available
Mobile Broadband accounts.
Sample name Description
Proximity sample This sample demonstrates how to use the PeerFinder and
(Windows 8) ProximityDevice classes to communicate with nearby computers.
You can use the Proximity API to exchange small messages during
a tap gesture or set up a socket connection between peer apps.
Creating a Windows This sample shows how to create a component in C++/CX that's
Runtime in-process used in C++/CX, JavaScript, and C# client code. The OvenServer
component sample project contains a runtime class named Oven , which implements an
(C++CX) (Windows 8) IOven interface and an IAppliance interface.
Device auto rotation This sample shows how to use the DisplayProperties class to
preferences sample handle and verify device rotation events.
(Windows 8)
Real-time communication This sample demonstrates how to use the low latency feature to
sample (Windows 8) enable real-time communication applications.
Sharing content source This sample demonstrates how an app can share content with
app sample (Windows 8) another app. This sample uses classes from the
Windows.ApplicationModel.DataTransfer namespace.
Search contract sample This sample shows how to let users search your app when they
(Windows 8) select the Search charm and open the search pane. And, how to use
the search pane to display suggestions for users' queries.
Raw notifications sample This sample shows how to use raw notifications, which are push
(Windows 8) notifications with no associated UI that perform a background task
for the app.
Direct2D basic image This sample shows how to load an image, apply the Gaussian blur
effects sample (Windows 8) effect to it, and then display it in a Windows::UI::Core::CoreWindow .
Direct2D effects on This sample shows how to apply image effects to Direct2D
primitives sample primitives. This sample draws rounded rectangles using Direct2D
(Windows 8) and then draws DirectWrite text in the middle of the rectangles.
Then it applies an effect graph to it.
Association launching This sample shows you how to launch the user's default app for file
sample (Windows 8) type or a protocol. You can also learn how to enable your app to be
the default app for a file type or a protocol.
Sample name Description
AtomPub sample This sample demonstrates how to access, create, update, and
(Windows 8) remove syndicated content feeds from the web. It uses the
Windows Runtime implementation of the Atom Publication
standard.
Certificate enrollment This sample demonstrates how to create and enroll a certificate in a
sample (Windows 8) certification hierarchy. To obtain an evaluation copy of Windows 8,
go to Windows 8. To obtain an evaluation copy of Microsoft Visual
Studio 2012, go to Visual Studio 2012.
Clipboard app sample This sample demonstrates how an app can use clipboard
(Windows 8) commands, including copy, paste, cut, and move. This sample uses
classes from the Windows.ApplicationModel.DataTransfer
namespace.
Direct2D composite effect This sample shows the wide range of composite and blend modes
modes sample (Windows available from Direct2D.
8)
Direct3D bump mapping This sample demonstrates bump mapping using a normal map and
sample (Windows 8) per-pixel lighting.
Calendar details and math This sample demonstrates how to use the Calendar class in the
sample (Windows 8) Windows.Globalization namespace to manipulate and process dates
based on a calendar system and the user's globalization
preferences.
Device enumeration This sample shows how to use the Device Enumeration API to find
sample (Windows 8) available devices and look for device information. The sample
presents two scenarios: In the first scenario, the Device Enumeration
API is used to look for specific device interfaces.
DirectWrite paragraph text This sample shows how to use DirectWrite and Direct2D to render
sample (Windows 8) paragraph text to a CoreWindow . And, apply justification and
character spacing to the layout.
XAML data binding sample This sample demonstrates basic data binding techniques using the
(Windows 8) Binding class and Binding markup extension.
Direct2D effects photo This sample shows various common photo manipulation techniques
adjustment app sample using Direct2D Effects. This sample is divided into several parts.
Sample name Description
(Windows 8) Lesson 1: Shows the basics of loading and drawing an image using
Direct2D Effects.
Windows Audio Session Demonstrates how to do various audio related tasks using the
(WASAPI) sample Windows Audio Session API (WASAPI).
(Windows 8)
User domain name sample This sample demonstrates the domain-related functionality
(Windows 8) provided by the UserInformation class of the
Windows.System.UserProfile namespace. The UserInformation class
enables an app to get and set information about the user.
USSD message This sample demonstrates network account management using the
management sample USSD protocol with GSM-capable mobile broadband devices. USSD
(Windows 8) is typically used for account management of a mobile broadband
profile by the Mobile Network Operator (MNO).
Bing Maps Trip Optimizer The sample demonstrates how to use JavaScript and Visual C++
sample (Windows 8) and to create app for Windows 8 named Bing Maps Trip Optimizer.
Bing Maps Trip Optimizer uses JavaScript to define the UI, and C++
for a computationally expensive algorithm in parallel.
Direct2D and DirectWrite This sample shows how to use Direct2D and DirectWrite to render a
animated text on a path string of text along an animated, non-linear geometric path. The
sample (Windows 8) app renders "Hello, World!" repeated several times in different
languages along a Bezier curve.
Wi-Fi hotspot This sample demonstrates how to use the Windows 8 Mobile
authentication sample Broadband API ( Windows.Networking.NetworkOperators ) for Wi-Fi
(Windows 8) hotspot authentication. Use this mechanism as an alternative to
configuring static credentials for a Wi-Fi hotspot.
XAML images sample This sample demonstrates various techniques for displaying and
(Windows 8) manipulating images in your app using the Image control and the
BitmapImage class.
HomeGroup app sample This sample demonstrates how to use a HomeGroup to open, search,
(Windows 8) and share files. This sample uses some of the HomeGroup options
found in the Windows.Storage.Pickers and
Windows.Storage.KnownFolders .
UI contrast and settings This sample shows how to use the UI settings APIs in a basic C# or
sample (Windows 8) JavaScript app.
Folder enumeration This sample shows how to list the top-level files and folders inside a
sample (Windows 8) location. (For example, a folder, device, or network location.) And,
how to use queries to list all files inside a location by sorting them
into file groups.
Sample name Description
File picker sample This sample shows how to access files and folders by letting the
(Windows 8) user choose them through the file pickers. And, how to save a file
so that the user can specify the name, file type, and location of a file
to save.
File picker contracts This sample shows how an app can provide files, a save location,
sample (Windows 8) and real-time file updates to other apps through the file picker. It's
done by participating in the File Open Picker contract, File Save
Picker contract, and Cached File Updater contract.
Programmatic file search This sample shows how to query files in locations such as a folder,
sample (Windows 8) library, device, or network location. It uses Windows.Storage.Search
API. Important APIs in this sample include: QueryOptions class,
StorageFileQueryResult class, and others.
File and folder thumbnail This sample shows how to retrieve thumbnails for files and folders.
sample (Windows 8) It uses Windows.Storage.FileProperties API.
Input Manipulations and This sample demonstrates how to handle pointer input and process
gestures (C++) sample manipulations and gestures with the GestureRecognizer APIs in a
(Windows 8) Windows Store app using C++ and DirectX.
Direct3D HLSL fractal This sample demonstrates the use of Direct3D HLSL and
generator sample DirectCompute compute shaders to create fractal images.
(Windows 8)
XAML Direct2D lighting This sample demonstrates the lighting effects available in Direct2D
effects sample (Windows 8) Effects. The lighting effect properties are controlled by XAML
interface controls and then displayed using Direct2D via a XAML
SwapChainBackgroundPanel.
Direct2Dapp printing This sample demonstrates how to add Direct2D printing support to
sample (Windows 8) a Windows Store app. This sample shows how to use Direct2D
features to render the content of a Windows Store app for printing.
And, how to send the rendered content to the printer.
Direct2D printing images This sample demonstrates how to print Direct2D images and
and effects sample Direct2D effects in a Windows Store app.
(Windows 8)
Direct2D animated text This sample shows how to render text quickly by using the Direct2D
sample (Windows 8) FillOpacityMask method. The sample also responds to touch. A two
finger pinch can be used to zoom the text in and out.
Extended Linguistic This sample demonstrates the use of Extended Linguistic Services
Services (ELS) sample (ELS) in a Windows Store app. The sample implements scenarios
(Windows 8) that demonstrate the use of the three available ELS services. The
scenarios demonstrate how to request a specific service.
DirectWrite hit testing This sample shows how to use the hit-testing features of
sample (Windows 8) DirectWrite. They're used to determine which part of the displayed
text is being clicked or touched.
DirectWrite inline object This sample shows how to insert an inline object into a text layout,
sample (Windows 8) such as an image.
Bluetooth call control The Bluetooth CallControl sample demonstrates how to configure
sample (Windows 8) the default Bluetooth communications device for handling calls.
There are JavaScript, C#, C++, and VB.Net versions of this sample.
This sample requires knowledge of Windows events and event
handling.
Direct2D command list This sample demonstrates the use of a command list. It's used for
sample (Windows 8) recording a set of vector commands, creating an image brush from
the command list, and then filling a rectangle geometry with it. The
command list preserves resolution independence of the vector.
XInput and JavaScript This sample demonstrates how to wrap the XInput C++ API in a
controller sketch sample Windows Runtime component. Then, it calls it from a Windows
(Windows 8) Store app using JavaScript. This sample implements a sketch app
that lets you use the Xbox game controller to select line thickness
and more.
Direct2D convolve matrix This sample demonstrates the Direct2D Effects convolve matrix
effect sample (Windows 8) effect. This sample has some example convolution kernel matrices:
Passthrough (no-op), Box blur (width 5), Simple edge detect, Simple
sharpen, Emboss, Vertical smear (height 10) theses and more.
DirectX swap chain This sample shows how to receive CoreWindow events in a native
implementation sample application, and how to connect a DirectX swap chain to the
(Windows 8) application view.
Direct2D animation sample This sample shows how to use Direct2D to render and animate a
(Windows 8) Direct2D primitive along a spiral path.
Sharing content target app This sample demonstrates how an app can receive content shared
sample (Windows 8) from another app. This sample uses classes from the
Windows.ApplicationModel.DataTransfer and
Windows.ApplicationModel.DataTransfer.Share namespaces.
Direct2D save to image file This sample shows how to render to the screen using Direct2D and
sample (Windows 8) DirectWrite. And, how to save the rendered image to disk using the
WIC API.
Scaling according to DPI This sample describes how to build an app that scales according to
sample (Windows 8) the pixel density of the screen. It loads images of the right scale or
overrides default scaling. This sample uses the
Windows.Graphics.Display API.
Creating a Windows This sample shows how to create a component in C# that's used in
Runtime in-process C++/CX, JavaScript, and C# client code. The OvenServer project
component sample (C#) contains a runtime class named Oven , which implements an IOven
(Windows 8) interface and an IAppliance interface.
Push and periodic This sample shows how a client app can register and listen for push
notifications client-side notifications sent from a web server. Push notifications can be used
sample (Windows 8) to update a badge or a tile, raise a toast notification, or launch a
background task.
Portable device API sample This sample shows how to access the IPortableDevice COM API
(Windows 8) from a C++ app. To learn how to access the IPortableDevice COM
API from a Desktop C++ app, refer to the Portable Devices COM
API Sample.
PlayToReceiver sample This sample demonstrates how to create a software Play To receiver.
(Windows 8) To advertise the software Play To Receiver, click the Start Receiver
button. To stop the receiver, click the Stop Receiver button.
Lock screen This sample demonstrates how to use the LockScreen API to set the
personalization sample current user's lock screen image. This sample uses classes from the
(Windows 8) Windows.System.UserProfile namespace.
Credential locker sample This sample demonstrates how to use the WinRT PasswordVault
(Windows 8) APIs, and how to use the credential locker to store web credentials.
Specific scenarios include a single user with a single resource, and
multiple users with a single resource.
Sample name Description
Media engine native C++ This sample demonstrates video playback using the MediaEngine
video playback sample API in a native C++ app.
(Windows 8)
Media extensions sample This sample demonstrates how to use media extensions. You can
(Windows 8) apply effects to video, decode video, and create media streams
using scheme handlers.
Lock screen apps sample This sample shows how an app can have a presence on the lock
(Windows 8) screen—the screen that is shown when the computer is locked—
with a badge to provide basic status information or a tile to provide
more detailed status.
XAML text display sample This sample demonstrates how control the appearance of text in
(Windows 8) your app.
Direct3D sprite sample This sample provides a Direct3D implementation of sprite batch
(Windows 8) behaviors, similar to the XNA SpriteBatch API. Sprites are 2-D
bitmaps that can be transformed and managed independently in a
3-D scene, typically used in 2-D games.
Direct3D stereoscopic 3D This sample demonstrates how to add a stereoscopic 3-D effect to
sample (Windows 8) C++ apps by using Direct3D. It also demonstrates how to respond
to system stereo changes in Direct3D. The stereoscopic 3-D effect
requires a display that supports stereo 3-D.
Creating a Windows This sample shows how to create an in-process DLL component in
Runtime DLL component Microsoft Visual C++. It's used in C++/CX, JavaScript, and C# client
with C++ sample code. The OvenServer project contains a runtime class named Oven ,
(Windows 8) which implements an IOven interface.
Creating a Windows This sample shows how to create an out-of-process EXE component
Runtime EXE component in Microsoft Visual C++. It's used in C++/CX, JavaScript, and C#
with C++ sample client code. The OvenServer project contains a runtime class named
(Windows 8) Oven , which implements an IOven interface.
Microsoft C/C++ help and community
Article • 09/27/2022
Here's where to get help and information about how to write C++ code and use the
Visual Studio development tools.
Samples
Developer Code Samples: Contains downloadable sample code from Microsoft and
community contributors.
Product documentation
C++ in Visual Studio: Contains reference and conceptual documentation about
Visual C++.
Windows Developer Center: Contains information about how to use C++ and
other languages to develop apps for Windows.
You can also download and view the content locally in the offline Help Viewer. The
offline documentation is organized by books of related content, which are also updated
periodically. You can download the books you're interested in as they become available.
For more information, see Microsoft Help Viewer.
Many sections of the documentation are also available in PDF form. These sections have
a Download PDF link below the table of contents on Microsoft Learn.
Related sites
C++ Team Blog : Contains posts on various subjects by the experts on Microsoft's
C++ product team.
Shows: Contains video interviews and lectures. Select Browse all shows on the
Shows home page to find C++ content.
Visual Studio website : Contains articles and news about Visual Studio and related
development tools. This site also hosts Visual Studio downloads and
Redistributable files.
Microsoft Learn Q&A: Official Microsoft forums where you can post questions
about C++ and Visual Studio and get answers from Microsoft and from experts in
the community.
Visual Studio C++ Developer Community : Forums for reporting problems in the
C++ compiler and tools or the IDE, or for making product suggestions. You can
vote for your favorite ideas or bug reports, or add a new one. This site is
monitored by the development team.
How to report a problem with the
Microsoft C++ toolset or
documentation
Article • 03/02/2023
If you find problems in the Microsoft C++ compiler (MSVC), the linker, or other tools
and libraries, we want to know about them. When the issue is in our documentation, we
want to know about that, too.
In the following sections, read about what makes a good report. We describe how to
generate a repro for the kind of issue you found, and how to send your report to the
product team. Your reports are important to us and to other developers like you. Thank
you for helping us improve Microsoft C++!
1. Open the Developer Command Prompt that matches the Visual Studio version
and configuration architecture used to build your project. For example, if you build
by using Visual Studio 2017 on x64 for x64 targets, choose x64 Native Tools
Command Prompt for VS 2017. For more information, see Developer command
prompt shortcuts.
2. In the developer command prompt console window, enter the command cl /Bv.
Output
C:\Users\username\Source>cl /Bv
Microsoft (R) C/C++ Optimizing Compiler Version 19.14.26428.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
Compiler Passes:
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.exe:
Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c1.dll:
Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c1xx.dll:
Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\c2.dll:
Version 19.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\link.exe:
Version 14.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\mspdb140.dl
l: Version 14.14.26428.1
C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\1033\clui.d
ll: Version 19.14.26428.1
The best place to find this information is in the build log immediately after you
experience the problem. It ensures that the command line contains exactly the same
arguments that might contribute to the problem.
Inside this file, find the names of your source code files, followed by the command-
line arguments used to compile them, each on separate lines.
2. Locate the line that contains the name of the source code file where the problem
occurs. The line below it contains the corresponding cl.exe command arguments.
Copy and paste the entire command line into your report.
If the issue is that the compiler accepts invalid code and doesn't generate a diagnostic,
include that in your report.
To report a runtime behavior problem, include an exact copy of what the program
prints, and what you expect to see. Ideally, embed it in the output statement itself, for
example, printf("This should be 5: %d\n", actual_result); . If your program crashes
or hangs, mention that as well.
Add any other details that might help us diagnose the problem you found, such as any
work-arounds you discovered. Try not to repeat information found elsewhere in your
report.
The repro
A repro is a complete, self-contained source code example. It reproducibly demonstrates
the problem you found, hence the name. We need a repro so that we can reproduce the
error on our machines. The code should be sufficient by itself to create a basic
executable that compiles and runs. Or, that would compile and run, if not for the
problem you found. A repro isn't a code snippet. It should have complete functions and
classes, and contain all the necessary #include directives, even for the standard headers.
Minimal. Repros should be as small as possible yet still demonstrate exactly the
problem you found. Repros don't need to be complex or realistic. They only need
to show code that conforms to the Standard, or to the documented compiler
implementation. For a missing diagnostic, your repro should show the code that's
not conformant. Simple, to-the-point repros that contain only enough code to
demonstrate the problem are best. If you can eliminate or simplify the code and
remain conformant, and also leave the issue unchanged, then do so. You don't
need to include counter-examples of code that works.
Self-Contained. Repros should avoid unnecessary dependencies. If you can
reproduce the problem without third-party libraries, then do so. If you can
reproduce the problem without any library code besides simple output statements
(for example, puts("this shouldn't compile"); , std::cout << value; , and
printf("%d\n", value); ), then do so. It's ideal if the example can be condensed to
a single source code file, without reference to any user headers. Reducing the
amount of code we have to consider as a possible contributor to the problem is
enormously helpful to us.
Against the latest compiler version. Repros should use the most recent update to
the latest version of the toolset whenever possible. Or, use the most recent
prerelease version of the next update or next major release. Problems you may find
in older versions of the toolset are often fixed in newer versions. Fixes are
backported to older versions only in exceptional circumstances.
Checked against other compilers if relevant. Repros that involve portable C++
code should verify behavior against other compilers if possible. The C++ standard
ultimately determines program correctness, and no compiler is perfect. However,
when Clang and GCC accept your code without a diagnostic, and MSVC doesn't,
you probably found a bug in our compiler. (Other possibilities include differences
in Unix and Windows behavior, or different levels of C++ standards
implementation, and so on.) When all the compilers reject your code, then it's
likely that your code is incorrect. Seeing different error messages may help you
diagnose the issue yourself.
You can find lists of online compilers to test your code against in Online C++
compilers on the ISO C++ website, or this curated List of Online C++
Compilers on GitHub. Some specific examples include Wandbox and Compiler
Explorer .
7 Note
The online compiler websites are not affiliated with Microsoft. Many online
compiler websites are run as personal projects. Some of these sites may be
unavailable when you read this, but a search should find others you can use.
Problems in the compiler, linker, and in the libraries, tend to show themselves in
particular ways. The kind of problem you find will determine what kind of repro you
should include in your report. Without an appropriate repro, we have nothing to
investigate. Here are a few of the kinds of issues that you may see. We include
instructions on how to generate the kind of repro you should use to report each kind of
problem.
Frontend crashes occur during the parsing phase of the compiler. Typically, the compiler
emits Fatal Error C1001, and references the source code file and line number on which
the error occurred. It often mentions a file named msc1.cpp, but you can ignore this
detail.
Output
SandBoxHost.cpp
d:\o\dev\search\foundation\common\tools\sandbox\managed\managed.h(929):
fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'msc1.cpp', line 1369)
To work around this problem, try simplifying or changing the program near
the
locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
d:\o\dev\search\foundation\common\tools\sandbox\managed\managed.h(929):
note: This diagnostic occurred in the compiler generated function
'void
Microsoft::Ceres::Common::Tools::Sandbox::SandBoxedProcess::Dispose(bool)'
Internal Compiler Error in d:\o\dev\otools\bin\x64\cl.exe. You will be
prompted
to send an error report to Microsoft later.
INTERNAL COMPILER ERROR in 'd:\o\dev\otools\bin\x64\cl.exe'
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
For this kind of crash, provide a Link repro if you're using Link-Time Code Generation
(LTCG), enabled by the /GL command-line argument to cl.exe. If not, provide a
Preprocessed repro instead.
Here's example compiler output for a backend crash in which LTCG isn't used. If your
compiler output looks like the following, you should provide a Preprocessed repro.
Output
repro.cpp
\\officefile\public\tadg\vc14\comperror\repro.cpp(13) : fatal error C1001:
An internal error has occurred in the compiler.
(compiler file 'f:\dd\vctools\compiler\utc\src\p2\main.c', line 230)
To work around this problem, try simplifying or changing the program near
the
locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
INTERNAL COMPILER ERROR in
'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe'
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
If the line that begins with INTERNAL COMPILER ERROR mentions link.exe, rather than
cl.exe, LTCG was enabled. Provide a Link repro in this case. When it's not clear whether
LTCG was enabled from the compiler error message, examine the command-line
arguments. You copied them from your build log, in a previous step for the /GL
command-line argument.
Linker crash
Linker crashes occur during the linking phase, after the compiler has run. Typically, the
linker emits Linker Tools Error LNK1000.
7 Note
Output
Version 14.00.22816.0
ExceptionCode = C0000005
ExceptionFlags = 00000000
ExceptionAddress = 00007FF73C9ED0E6 (00007FF73C9E0000)
"z:\tools\bin\x64\link.exe"
NumberParameters = 00000002
ExceptionInformation[ 0] = 0000000000000000
ExceptionInformation[ 1] = FFFFFFFFFFFFFFFF
CONTEXT:
If incremental linking is enabled, and the crash occurred only after a successful initial
link, that is, only after the first full link on which a later incremental link is based, also
provide a copy of the object (.obj) and library (.lib) files that correspond to source files
modified after the initial link was completed.
For this kind of crash, provide a Link repro if you're using the /GL command-line
argument to cl.exe. Provide a Preprocessed repro if not.
Below are instructions for generating the various kinds of repros to use to report
different kinds of problems.
Preprocessed repros
A Preprocessed repro is a single source file that demonstrates a problem. It's generated
from the output of the C preprocessor. To create one, use the /P compiler option on the
original repro source file. This option inlines the included headers to remove
dependencies on other source and header files. The option also resolves macros, #ifdef
conditionals, and other preprocessor commands that could depend on your local
environment.
7 Note
Preprocessed repros are not as useful for problems that might be the result of bugs
in our standard library implementation, because we will often want to substitute
our latest, in-progress implementation to see whether we've already fixed the
problem. In this case, don't preprocess the repro, and if you can't reduce the
problem to a single source file, package your code into a .zip file or similar, or
consider using an IDE project repro. For more information, see Other repros.
2. Open the Developer Command Prompt that matches the Visual Studio version
and configuration architecture used to build your project.
If you're preprocessing a C++/CX source code file, or you're using the C++ Modules
feature, some more steps are required. For more information, see the sections below.
After you generate the preprocessed file, it's a good idea to make sure that the problem
still repros when you compile the preprocessed file.
3. Make a list of all of the referenced files. Leave out any Windows*.winmd files,
platform.winmd files, and mscorlib.dll.
To prepare to validate that the preprocessed file still reproduces the problem,
1. Create a new directory for the preprocessed file and copy it to the new directory.
2. Copy the .winmd files from your #using list to the new directory.
4. Edit the preprocessed file to remove any #using directives for mscorlib.dll.
5. Edit the preprocessed file to change any absolute paths to just the bare filenames
for the copied .winmd files.
Confirm that the preprocessed file still reproduces the problem, as above.
Preprocessed C++ Modules repros
If you're using the Modules feature of the C++ compiler, there are some different steps
required to create and validate a preprocessed repro.
2. Open the Developer Command Prompt that matches the Visual Studio version
and configuration architecture used to build your project.
5. Change to the directory that contains the repro project that built the module
interface (the .ifc output).
After you generate the preprocessed files, it's a good idea to make sure the problem still
repros when you use the preprocessed file.
1. In the developer console window, change back to the directory that contains your
repro project.
Finally, attach the preprocessed repro files (filename.i and modulename.i) along with the
.ifc output to your report.
Link repros
A link repro is the linker-generated contents of a directory, specified either by the
link_repro environment variable, or as an argument to the /LINKREPRO linker option. It
contains build artifacts that collectively demonstrate a problem that occurs at link time.
Examples include a backend crash involving Link-Time Code Generation (LTCG), or a
linker crash. These build artifacts are the ones needed as linker input so the problem can
be reproduced. A link repro can be created easily by using this environment variable. It
enables the linker's built-in repro generation capability.
2. Open the Developer Command Prompt that matches the Visual Studio version
and configuration architecture used to build your project.
3. In the developer command prompt console window, change to the directory that
contains your repro project.
4. Enter mkdir linkrepro to create a directory named linkrepro for the link repro. You
can use a different name to capture another link repro.
6. To build the repro project in Visual Studio, in the developer command prompt
console window, enter the command devenv. It ensures that the value of the
link_repro environment variable is visible to Visual Studio. To build the project at
the command line, use the command-line arguments captured above to duplicate
the repro build.
7. Build your repro project, and confirm that the expected problem occurred.
9. In the developer command prompt console window, enter the command set
link_repro= to clear the link_repro environment variable.
Finally, package the repro by compressing the entire linkrepro directory into a .zip file or
similar, and attach it to your report.
The /LINKREPRO linker option has the same effect as the link_repro environment
variable. You can use the /LINKREPROTARGET option to specify the name to filter on for
the generated link repro. To use /LINKREPROTARGET, you must also specify the /OUT
linker option.
1. Create a directory to hold the link repro. We'll refer to the full directory path you
create as directory-path. Use double quotes around the path if it includes spaces.
3. Build your repro project, and confirm that the expected problem has occurred.
Finally, package the repro by compressing the entire directory-path link repro directory
into a .zip file or similar, and attach it to your report.
Other repros
If you can't reduce the problem to a single source file or preprocessed repro, and the
problem doesn't require a link repro, we can investigate an IDE project. All the guidance
on how to create a good repro still applies: The code ought to be minimal and self-
contained. The problem should occur in our most recent tools, and if relevant, shouldn't
be seen in other compilers.
Create your repro as a minimal IDE project, then package it by compressing the entire
directory structure into a .zip file or similar and attach it to your report.
Regardless of how you submit your report, Microsoft respects your privacy.
Microsoft is committed to compliance with all data privacy laws and regulations.
For information about how we treat the data that you send us, see the Microsoft
Privacy Statement .
Reporting your problem through the Report a Problem tool is easy and convenient
from the IDE. You can access it from the title bar by choosing the Send Feedback icon
next to the Quick Launch search box. Or, you can find it on the menu bar in Help >
Send Feedback > Report a Problem.
When you choose to report a problem, first search the Developer Community for similar
problems. In case your problem has been reported before, upvote the report and add
comments with more specifics. If you don't see a similar problem, choose the Report
new problem button at the bottom of the Visual Studio Feedback dialog and follow the
steps to report your problem.
Beneath the community tabs, near the top of each page, is a search box. You can use it
to find posts that report problems similar to yours. You may find a solution or other
useful information related to your problem is already available. If someone has reported
the same problem before, then upvote and comment on that report, rather than create
a new problem report. To comment, vote, or report a new problem, you may be asked to
sign in to your Visual Studio account. The first time you sign in, you have to agree to
give the Developer Community app access to your profile.
For issues with the C++ compiler, linker, and other tools and libraries, first search the
C++ Developer Community page. If you search for your problem, and it isn't already
reported, choose the Report a problem button next to the search box. You can include
your repro code and command line, screenshots, links to related discussions, and any
other information you think is relevant and useful.
Tip
Information in the initial Developer Community report will always be public. If this
is a concern, see the next section about Reports and privacy.
Tip
For other kinds of problems you might find in Visual Studio that are unrelated to
the C++ toolset (For example, UI issues, broken IDE functionality, or general
crashes), use the Report a Problem tool in the IDE. This is the best choice, due to
its screenshot capabilities and its ability to record UI actions that lead to the
problem you found. These kinds of errors can also be looked up on the Visual
Studio Developer Community site. For more information, see How to report a
problem with Visual Studio.
If you're concerned about revealing your identity, create a new Microsoft account that
doesn't disclose any details about you. Use this account to create your report.
Don't put anything you want to keep private in the title or content of the initial
report, which is public. Instead, say that you'll send details privately in a separate
comment. To make sure that your report is directed to the right people, include
cppcompiler in the topic list of your problem report. Once the problem report is
created, it's now possible to specify who can see your replies and attachments.
2. In the reply editor, use the dropdown control below the Submit and Cancel
buttons to specify the audience for your reply. Only the people you specify can see
these private replies and any images, links, or code you include in them. Choose
Viewable by moderators and the original poster to limit visibility to Microsoft
employees and yourself.
3. Add the description and any other information, images, and file attachments
needed for your repro. Choose the Submit button to send this information
privately.
There's a 2GB limit on attached files, and a maximum of 10 files. For any larger
uploads, request an upload URL in your private comment.
Any replies under this comment have the same restricted visibility you specified. It's true
even if the dropdown control on replies doesn't show the restricted visibility status
correctly.
To maintain your privacy and keep your sensitive information out of public view, be
careful. Keep all interaction with Microsoft to replies under the restricted comment.
Replies to other comments may cause you to accidentally disclose sensitive information.
You create a documentation issue on GitHub when you use the documentation
feedback button. The issue is automatically filled in with some information about the
page you created the issue on. That's how we know where the problem is located, so
don't edit this information. Just append the details about what's wrong, and if you like, a
suggested fix. Our C++ docs are open source , so if you'd like to submit a fix yourself,
you can. For more information about how you can contribute to our documentation, see
our Contributing guide on GitHub.
Feedback
Was this page helpful? Yes No
If you haven't downloaded and installed Visual Studio and the Microsoft C/C++ tools
yet, here's how to get started.
7 Note
This topic applies to installation of Visual Studio on Windows. Visual Studio Code
is a lightweight, cross-platform development environment that runs on Windows,
Mac, and Linux systems. The Microsoft C/C++ for Visual Studio Code extension
supports IntelliSense, debugging, code formatting, auto-completion. Visual Studio
for Mac doesn't support Microsoft C++, but does support .NET languages and
cross-platform development. For installation instructions, see Install Visual Studio
for Mac.
Want to know more about what else is new in this version? See the Visual Studio release
notes.
1. Check the system requirements. These requirements help you know whether your
computer supports Visual Studio 2022.
2. Apply the latest Windows updates. These updates ensure that your computer has
both the latest security updates and the required system components for Visual
Studio.
3. Reboot. The reboot ensures that any pending installs or updates don't hinder the
Visual Studio install.
4. Free up space. Remove unneeded files and applications from your %SystemDrive%
by, for example, running the Disk Cleanup app.
For questions about running previous versions of Visual Studio side by side with Visual
Studio 2022, see the Visual Studio 2022 Platform Targeting and Compatibility page.
If you receive a User Account Control notice, choose Yes to allow the bootstrapper
to run.
2. We'll ask you to acknowledge the Microsoft License Terms and the Microsoft
Privacy Statement . Choose Continue.
1. Find the workload you want in the Installing Visual Studio screen.
For core C and C++ support, choose the "Desktop development with C++"
workload. It comes with the default core editor, which includes basic code editing
support for over 20 languages, the ability to open and edit code from any folder
without requiring a project, and integrated source code control.
The Installation details pane lists the included and optional components installed
by each workload. You can select or deselect optional components in this list. For
example, to support development by using the Visual Studio 2017 or 2015
compiler toolsets, choose the MSVC v141 or MSVC v140 optional components. You
can add support for MFC, the experimental Modules language extension,
IncrediBuild, and more.
2. After you choose the workload(s) and optional components you want, choose
Install.
Next, status screens appear that show the progress of your Visual Studio
installation.
Tip
At any time after installation, you can install workloads or components that you
didn't install initially. If you have Visual Studio open, go to Tools > Get Tools and
Features... which opens the Visual Studio Installer. Or, open Visual Studio Installer
from the Start menu. From there, you can choose the workloads or components
that you wish to install. Then, choose Modify.
Another way that you can change the default language is by running the installer from
the command line. For example, you can force the installer to run in English by using the
following command: vs_installer.exe --locale en-US . The installer will remember this
setting when it's run the next time. The installer supports the following language tokens:
zh-cn, zh-tw, cs-cz, en-us, es-es, fr-fr, de-de, it-it, ja-jp, ko-kr, pl-pl, pt-br, ru-ru, and tr-tr.
Step 7 - Change the installation location (Optional)
You can reduce the installation footprint of Visual Studio on your system drive. You can
choose to move the download cache, shared components, SDKs, and tools to different
drives, and keep Visual Studio on the drive that runs it the fastest.
) Important
You can select a different drive only when you first install Visual Studio. If you've
already installed it and want to change drives, you must uninstall Visual Studio and
then reinstall it.
3. In the search box, enter the type of app you want to create to see a list of available
templates. The list of templates depends on the workload(s) that you chose during
installation. To see different templates, choose different workloads.
You can also filter your search for a specific programming language by using the
Language drop-down list. You can filter by using the Platform list and the Project
type list, too.
4. Visual Studio opens your new project, and you're ready to code!
When Visual Studio is running, you're ready to continue to the next step.
Next Steps
Create a C++ project
Create a C++ console app project
Article • 07/06/2023
The usual starting point for a C++ programmer is a "Hello, world!" application that runs
on the command line. That's what you create in Visual Studio in this step.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed
and running on your computer. If it's not installed yet, see Install C++ support in
Visual Studio.
1. In Visual Studio, open the File menu and choose New > Project to open the Create
a new Project dialog. Select the Console App template that has C++, Windows,
and Console tags, and then choose Next.
2. In the Configure your new project dialog, enter HelloWorld in the Project name
edit box. Choose Create to create the project.
Visual Studio creates a new project. It's ready for you to add and edit your source
code. By default, the Console App template provides source code for a "Hello
World" app, like this:
When the code looks like this in the editor, you're ready to go on to the next step
and build your app.
I ran into a problem.
Next steps
Build and run a C++ project
Troubleshooting guide
Come here for solutions to common issues when you create your first C++ project.
To install Desktop development with C++, you can run the installer right from the New
Project dialog. Choose the Install more tools and features link at the bottom of the
template list to start the installer. If the User Account Control dialog requests
permissions, choose Yes. In the installer, make sure the Desktop development with C++
workload is checked. Then choose Modify to update your Visual Studio installation.
If another project with the same name already exists, choose another name for your
project. Or, delete the existing project and try again. To delete an existing project, delete
the solution folder (the folder that contains the helloworld.sln file) in File Explorer.
Go back.
Build and run a C++ console app
project
Article • 07/01/2024
In Create a C++ console app project you created a C++ console app project and
entered your code. Now you can build and run it within Visual Studio. Then, run it as a
stand-alone app from the command line.
Prerequisites
Have Visual Studio with the Desktop development with C++ workload installed
and running on your computer. If it's not installed, follow the steps in Install C++
support in Visual Studio.
Create a "Hello, World!" project. By default, it contains code to print Hello World! .
If you haven't done this step yet, follow the steps in Create a C++ console app
project.
If Visual Studio looks like this, you're ready to build and run your app:
2. To run the code, on the menu bar, choose Debug, Start without debugging.
A console window opens and then runs your app. When you start a console app in
Visual Studio, it runs your code, then prints "Press any key to continue . . ." to give
you a chance to see the output.
Congratulations! You created your first "Hello, world!" console app in Visual Studio!
Press a key to dismiss the console window and return to Visual Studio.
1. In Solution Explorer, select the HelloWorld solution (not the HelloWorld project)
and right-click to open the context menu. Choose Open Folder in File Explorer to
open a File Explorer window in the HelloWorld solution folder.
2. In the File Explorer window, open the x64 folder and then the Debug folder. This
folder contains your app, HelloWorld.exe , and debugging files. Hold down the
Shift key and right-click on HelloWorld.exe to open the context menu. Choose
Copy as path to copy the path to your app to the clipboard. If you see
HelloWorld.exe.recipe , it's because you did the Open Folder in File Explorer step
3. To open a command prompt window, press Windows+R to open the Run dialog.
Enter cmd.exe in the Open textbox, then choose OK to run a command prompt
window.
4. In the command prompt window, right-click to paste the path to your app into the
command prompt. Press Enter to run your app.
Congratulations, you built and ran a console app in Visual Studio!
Next Steps
Once you build and run this simple app, you're ready for more complex projects. For
more information, see Using the Visual Studio IDE for C++ Desktop Development. It has
more detailed walkthroughs that explore the capabilities of Microsoft C++ in Visual
Studio.
Troubleshooting guide
Come here for solutions to common issues when you create your first C++ project.
Go back.
first HelloWorld in the path. This folder also contains a x64\Debug folder, where your
app is.
You can also navigate to the solution x64\Debug folder at the command line to run your
app. Your app won't run from other directories without specifying the path to the app.
However, you can copy your app to another directory and run it from there. It's also
possible to copy it to a directory specified by your PATH environment variable, then run
it from anywhere.
If you don't see Copy as path in the shortcut menu, dismiss the menu, and then hold
down the Shift key while you open it again. This command is just for convenience. You
can also copy the path to the folder from the File Explorer search bar, and paste it into
the Run dialog, and then enter the name of your executable at the end. It's just a little
more typing, but it has the same result.
Go back.
Feedback
Was this page helpful? Yes No
The usual starting point for a C++ programmer is a "Hello, world!" application that runs
on the command line. You'll start with that in this article, and then we move on to
something more challenging: a calculator app.
Prerequisites
Visual Studio with the Desktop development with C++ workload installed and
running on your computer. To install it, see Install C++ support in Visual Studio.
This tutorial demonstrates a feature called edit and continue which allows you to
make changes to your code while the app is running. To enable edit and continue,
from the main menu select Tools > Options > Debugging > General and ensure
that Require source files to exactly match the original version is checked.
1. Start Visual Studio--the Visual Studio Start dialog box appears. Select Create a new
project to get started.
2. In the list of project templates, select Console App, then select Next.
) Important
Make sure you select the C++ version of the Console App template. It has the
C++, Windows, and Console tags, and the icon has "++" in the corner.
3. In the Configure your new project dialog box, select the Project name text box,
name your new project CalculatorTutorial, then select Create.
An empty C++ Windows console application 'Hello World' app is created. Console
applications use a Windows console window to display output and accept user
input. In Visual Studio, an editor window opens and shows the generated code:
C++
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
1. To build your project, select Build Solution from the Build menu. The Output
window shows the results of the build process.
2. To run the code, on the menu bar, select Debug, Start without debugging
(Ctrl+F5).
A console window opens and then runs your app.
When you start a console app in Visual Studio, it runs your code, then prints "Press
any key to close this window . . ." to give you a chance to see the output.
Congratulations! You created your first "Hello, world!" console app in Visual Studio!
3. Press a key to dismiss the console window and return to Visual Studio.
You now have the tools to build and run your app after every change, to verify that the
code still works as you expect. Later, we show you how to debug it if it doesn't.
1. Replace the contents of the CalculatorTutorial.cpp file with the following code so
that it matches this example:
C++
#include <iostream>
int main()
{
cout << "Calculator Console Application" << endl << endl;
cout << "Please enter the operation to perform. Format: a+b | a-b |
a*b | a/b"
<< endl;
return 0;
}
2. To save the file, press Ctrl+S, or select the Save icon near the top of the IDE, the
floppy disk icon in the toolbar under the menu bar.
3. To run the application, press Ctrl+F5 or go to the Debug menu and select Start
Without Debugging. You should see a console window appear that displays the
text specified in the code.
Two new files get added to your project. To save all your changed files at once,
press Ctrl+Shift+S. It's a keyboard shortcut for File > Save All. There's also a
toolbar button for Save All, an icon of two floppy disks, found beside the Save
button. In general, it's good practice to do Save All frequently, so you don't miss
any files when you save.
The Add Class wizard creates .h and .cpp files that have the same name as the
class. You can see a full list of your project files in the Solution Explorer window,
visible on the side of the IDE. If the window isn't visible, you can open it from the
menu bar: select View > Solution Explorer.
You can open a file by double-clicking it in the Solution Explorer window. Double-
click Calculator.h to open it.
2. Replace the contents of Calculator.h with the following code so that the file now
looks like this:
C++
#pragma once
class Calculator
{
public:
double Calculate(double x, char oper, double y);
};
This code declares a new function called Calculate , which we use to run
math operations for addition, subtraction, multiplication, and division.
C++ code is organized into header ( .h ) files and source ( .cpp ) files.
Several other file extensions are supported by various compilers, but
these are the main ones to know about. Functions and variables are
normally declared, that is, given a name and a type, in header files, and
implemented, or given a definition, in source files. To access code defined
in another file, you can use #include "filename.h" , where filename.h is
the name of the file that declares the variables or functions you want to
use.
It's good practice to organize your code into different files based on what
it does, so it's easy to find the code you need later. In our case, we define
the Calculator class separately from the file containing the main()
function, but we plan to reference the Calculator class in main() .
4. Switch to the Calculator.cpp file in the editor window. Replace the contents of
Calculator::Calculate(double x, char oper, double y) with:
C++
If you build and run the code again at this point, it will immediately exit after asking
which operation to perform. So, modify the main function to do multiple calculations.
C++
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
result = c.Calculate(x, oper, y);
cout << "Result " << "of " << x << oper << y << " is: " <<
result << endl;
}
return 0;
}
Since C++ programs always start at the main() function, we need to call
our other code from there, so a #include statement is needed.
Some initial variables x , y , oper , and result are declared to store the
first number, second number, operator, and final result, respectively. It's
always good practice to give them some initial values to avoid undefined
behavior, which is what is done here.
The Calculator c; line declares an object named 'c' as an instance of the
Calculator class. The class itself is just a blueprint for how calculators
work; the object is the specific calculator that does the math.
The while (true) statement is a loop. The code inside the loop continues
to execute over and over again as long as the condition inside the ()
holds true. Since the condition is simply listed as true , it's always true, so
the loop runs forever. To close the program, the user must manually close
the console window. Otherwise, the program always waits for new input.
The cin keyword is used to accept input from the user. This input stream
is smart enough to process a line of text entered in the console window
and place it inside each of the variables listed, in order, assuming the user
input matches the required specification. You can modify this line to
accept different types of input such as more than two numbers--though
the Calculate() function would also need to be updated to handle this.
The c.Calculate(x, oper, y); expression calls the Calculate function
defined earlier, and supplies the entered input values. The function then
returns a number that gets stored in result .
Finally, result is printed to the console, so the user sees the result of the
calculation.
2. Enter 5+5 , and press Enter. Verify that the result is 10.
Debug the app
Since the user is free to type anything into the console window, let's make sure the
calculator handles unexpected input. Instead of running the program, let's debug it so
we can inspect what it's doing step-by-step.
Now when we debug the program, execution pauses at that line. We already have
a rough idea that the program works for simple cases. Since we don't want to
pause execution every time we call Calculate() , let's make the breakpoint
conditional.
2. Right-click the red dot that represents the breakpoint, and select Conditions. In
the edit box for the condition, enter (y == 0) && (oper == '/') . Select the Close
button to save the breakpoint condition.
Now, execution will pause at the breakpoint when the app tries to divide by 0.
3. To debug the program, press F5, or select the Local Windows Debugger toolbar
button that has the green arrow icon. In your console app, if you enter something
like "5 - 0", the program behaves normally and keeps running. However, if you
type "10 / 0", it pauses at the breakpoint. You can put any number of spaces
between the operator and numbers: cin is smart enough to parse the input
appropriately.
To see all of the variables from that function, switch to the Locals window. You can
modify the values of these variables while debugging to see what effect they would
have on the program. In this case, we leave them alone.
You can also hover over variables in the code to see their current values at the point
where execution is currently paused. Make sure the editor window is in focus by clicking
on it first.
Continue debugging
1. The yellow arrow on the left shows the current point of execution. The current line
calls Calculate , so press F11 to Step Into the function. Now you're executing code
in the body of the Calculate function. Be careful with Step Into because it steps
into any functions on the line you're on, including standard library functions. It's
fine to step into the standard library, but you may be more interested in focusing
on your code instead of library code.
2. Now that the point of execution is at the start of the Calculate function, press F10
to move to the next line in the program's execution. F10 is also known as Step
Over. You can use Step Over to move from line to line, without delving into the
details of what is occurring in each part of the line. In general, you should use Step
Over instead of Step Into unless you want to dive more deeply into code that is
being called from elsewhere (as you did to reach the body of Calculate ).
3. Continue using F10 to Step Over each line until you get back to the main()
function in the other file, and stop on the cout line.
The program is doing what's expected: it takes the first number, and divides it by
the second. On the cout line, hover over the result variable or take a look at
result in the Autos window. Its value inf , which doesn't look right, so let's fix it.
The cout line just outputs whatever value is stored in result , so when you step
one more line forward using F10, the console window displays:
This result is because division by zero is undefined, so the program doesn't have a
numerical answer for the requested operation.
C++
#include <iostream>
#include "Calculator.h"
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
char oper = '+';
Calculator c;
while (true)
{
cin >> x >> oper >> y;
if (oper == '/' && y == 0)
{
cout << "Math error: Attempted to divide by zero!" << endl;
continue;
}
else
{
result = c.Calculate(x, oper, y);
}
cout << "Result " << "of " << x << oper << y << " is: " <<
result << endl;
}
return 0;
}
2. Press F5 once. Program execution continues all the way until it has to pause to ask
for user input. Enter 10 / 0 again. Now, a more helpful message is printed. The
user is asked for more input, and the program continues executing normally.
7 Note
When you edit code while in debugging mode, there is a risk of code
becoming stale. This happens when the debugger is still running your old
code, and has not yet updated it with your changes. The debugger displays a
dialog to inform you when this happens. Sometimes, you may need to press
F5 to refresh the code being executed. In particular, if you make a change
inside a function while the point of execution is inside that function, you need
to step out of the function, then back into it again to get the updated code. If
that doesn't work and you see an error message, you can stop debugging by
clicking on the red square in the toolbar under the menus at the top of the
IDE, then start debugging again by entering F5 or by choosing the green
"play" arrow beside the stop button on the toolbar.
Another reason edit and continue may fail is if you see a message that says
"The Require source files to exactly match the original version setting under
Debug->Options->General needs to be enabled..." To fix this, from the main
menu select Tools > Options > Debugging > General and ensure that
Require source files to exactly match the original version is checked.
F5 (or Debug > Start Debugging) starts a debugging session if one isn't
already active, and runs the program until a breakpoint is hit or the
program needs user input. If no user input is needed and no breakpoint
is available to hit, the program terminates and the console window closes
itself when the program finishes running. If you have something like a
"Hello World" program to run, use Ctrl+F5 or set a breakpoint before you
press F5 to keep the window open.
Ctrl+F5 (or Debug > Start Without Debugging) runs the application
without going into debug mode. This is slightly faster than debugging,
and the console window stays open after the program finishes executing.
F10 (known as Step Over) lets you iterate through code, line-by-line, and
visualize how the code is run and what variable values are at each step of
execution.
F11 (known as Step Into) works similarly to Step Over, except it steps into
any functions called on the line of execution. For example, if the line
being executed calls a function, pressing F11 moves the pointer into the
body of the function, so you can follow the function's code being run
before coming back to the line you started at. Pressing F10 steps over the
function call and just moves to the next line; the function call still
happens, but the program doesn't pause to show you what it's doing.
Tip
Git is the most widely used modern version control system, so whether you're a
professional developer or you're learning how to code, Git can be very useful. If
you're new to Git, the https://git-scm.com/ website is a good place to start.
There, you can find cheat sheets, a popular online book, and Git Basics videos.
To associate your code with Git, you start by creating a new Git repository where your
code is located. Here's how:
1. In the status bar at the bottom-right corner of Visual Studio, select Add to Source
Control, and then select Git.
2. In the Create a Git repository dialog box, sign in to GitHub.
Tip
Whether your repository is public or private, it's best to have a remote backup
of your code stored securely on GitHub. Even if you aren't working with a
team, a remote repository makes your code available to you from any
computer.
After you create your repository, status details appear in the status bar.
The first icon with the arrows shows how many outgoing/incoming commits are in
your current branch. You can use this icon to pull any incoming commits or push
any outgoing commits. You can also choose to view these commits first. To do so,
select the icon, and then select View Outgoing/Incoming.
The second icon with the pencil shows the number of uncommitted changes to
your code. You can select this icon to view those changes in the Git Changes
window.
To learn more about how to use Git with your app, see the Visual Studio version control
documentation.
Next steps
Learn more about Visual Studio for C++
Feedback
Was this page helpful? Yes No
) Important
To get you up to speed with using C++/WinRT, this topic walks through a simple code
example based on a new Windows Console Application (C++/WinRT) project. This
topic also shows how to add C++/WinRT support to a Windows Desktop application
project.
7 Note
While we recommend that you develop with the latest versions of Visual Studio and
the Windows SDK, if you're using Visual Studio 2017 (version 15.8.0 or later), and
targeting the Windows SDK version 10.0.17134.0 (Windows 10, version 1803), then
a newly created C++/WinRT project may fail to compile with the error "error C3861:
'from_abi': identifier not found", and with other errors originating in base.h. The
solution is to either target a later (more conformant) version of the Windows SDK,
or set project property C/C++ > Language > Conformance mode: No (also, if
/permissive- appears in project property C/C++ > Language > Command Line
under Additional Options, then delete it).
A C++/WinRT quick-start
Create a new Windows Console Application (C++/WinRT) project.
C++/WinRT
// pch.h
#pragma once
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Web.Syndication.h>
#include <iostream>
C++/WinRT
// main.cpp
#include "pch.h"
int main()
{
winrt::init_apartment();
Let's take the short code example above piece by piece, and explain what's going on in
each part.
C++/WinRT
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Web.Syndication.h>
With the default project settings, the included headers come from the Windows SDK,
inside the folder
%WindowsSdkDir%Include<WindowsTargetPlatformVersion>\cppwinrt\winrt . Visual Studio
includes that path in its IncludePath macro. But there's no strict dependency on the
Windows SDK, because your project (via the cppwinrt.exe tool) generates those same
headers into your project's $(GeneratedFilesDir) folder. They'll be loaded from that
folder if they can't be found elsewhere, or if you change your project settings.
The headers contain Windows APIs projected into C++/WinRT. In other words, for each
Windows type, C++/WinRT defines a C++-friendly equivalent (called the projected type).
A projected type has the same fully-qualified name as the Windows type, but it's placed
in the C++ winrt namespace. Putting these includes in your precompiled header
reduces incremental build times.
) Important
Whenever you want to use a type from a Windows namespaces, you must #include
the corresponding C++/WinRT Windows namespace header file, as shown above.
The corresponding header is the one with the same name as the type's namespace.
For example, to use the C++/WinRT projection for the
Windows::Foundation::Collections::PropertySet runtime class, include the
winrt/Windows.Foundation.Collections.h header.
C++/WinRT
The using namespace directives are optional, but convenient. The pattern shown above
for such directives (allowing unqualified name lookup for anything in the winrt
namespace) is suitable for when you're beginning a new project and C++/WinRT is the
only language projection you're using inside of that project. If, on the other hand, you're
mixing C++/WinRT code with C++/CX and/or SDK application binary interface (ABI)
code (you're either porting from, or interoperating with, one or both of those models),
then see the topics Interop between C++/WinRT and C++/CX, Move to C++/WinRT
from C++/CX, and Interop between C++/WinRT and the ABI.
C++/WinRT
winrt::init_apartment();
C++/WinRT
Stack-allocate two objects: they represent the uri of the Windows blog, and a
syndication client. We construct the uri with a simple wide string literal (see String
handling in C++/WinRT for more ways you can work with strings).
C++/WinRT
SyndicationFeed syndicationFeed =
syndicationClient.RetrieveFeedAsync(rssFeedUri).get();
C++/WinRT
SyndicationFeed.Items is a range, defined by the iterators returned from begin and end
functions (or their constant, reverse, and constant-reverse variants). Because of this, you
can enumerate Items with either a range-based for statement, or with the std::for_each
template function. Whenever you iterate over a Windows Runtime collection like this,
you'll need to #include <winrt/Windows.Foundation.Collections.h> .
C++/WinRT
// Omitted: there's a little bit of extra work here to remove the trademark
symbol from the title text.
std::wcout << titleAsHstring.c_str() << std::endl;
Gets the feed's title text, as a winrt::hstring object (more details in String handling in
C++/WinRT). The hstring is then output, via the c_str function, which reflects the pattern
used with C++ Standard Library strings.
As you can see, C++/WinRT encourages modern, and class-like, C++ expressions such
as syndicationItem.Title().Text() . This is a different, and cleaner, programming style
from traditional COM programming. You don't need to directly initialize COM, nor work
with COM pointers.
Nor do you need to handle HRESULT return codes. C++/WinRT converts error HRESULTs
to exceptions such as winrt::hresult-error for a natural and modern programming style.
For more info about error-handling, and code examples, see Error handling with
C++/WinRT.
But this section shows you how you can add C++/WinRT support to any Windows
Desktop application project that you might have. If you don't have an existing Windows
Desktop application project, then you can follow along with these steps by first creating
one. For example, open Visual Studio and create a Visual C++ > Windows Desktop >
Windows Desktop Application project.
You can optionally install the C++/WinRT Visual Studio Extension (VSIX) and the
NuGet package. For details, see Visual Studio support for C++/WinRT.
Confirm that you're not affected by Why won't my new project compile?.
Because C++/WinRT uses features from the C++17 standard, set project property
C/C++ > Language > C++ Language Standard to ISO C++17 Standard (/std:c++17).
The precompiled header
The default project template creates a precompiled header for you, named either
framework.h , or stdafx.h . Rename that to pch.h . If you have a stdafx.cpp file, then
rename that to pch.cpp . Set project property C/C++ > Precompiled Headers >
Precompiled Header to Create (/Yc), and Precompiled Header File to pch.h.
Find and replace all #include "framework.h" (or #include "stdafx.h" ) with #include
"pch.h" .
C++/WinRT
// pch.h
...
#include <winrt/base.h>
Linking
The C++/WinRT language projection depends on certain Windows Runtime free (non-
member) functions, and entry points, that require linking to the WindowsApp.lib
umbrella library. This section describes three ways of satisfying the linker.
The first option is to add to your Visual Studio project all of the C++/WinRT MSBuild
properties and targets. To do this, install the Microsoft.Windows.CppWinRT NuGet
package into your project. Open the project in Visual Studio, click Project > Manage
NuGet Packages... > Browse, type or paste Microsoft.Windows.CppWinRT in the search
box, select the item in search results, and then click Install to install the package for that
project.
You can also use project link settings to explicitly link WindowsApp.lib . Or, you can do it
in source code (in pch.h , for example) like this.
C++/WinRT
You can now compile and link, and add C++/WinRT code to your project (for example,
code similar to that shown in the A C++/WinRT quick-start section, above).
Authoring APIs with C++/WinRT is a little more involved than consuming them, because
you must use IDL to define the shape of the API before you can implement it. There's a
walkthrough of doing that in XAML controls; bind to a C++/WinRT property.
XAML applications
This scenario is about building applications and controls on the XAML UI framework.
Working in a XAML application amounts to a combination of consuming and authoring.
But since XAML is the dominant UI framework on Windows today, and its influence over
the Windows Runtime is proportionate to that, it deserves its own category of scenario.
Be aware that XAML works best with programming languages that offer reflection. In
C++/WinRT, you sometimes have to do a little extra work in order to interoperate with
the XAML framework. All of those cases are covered in the documentation. Good places
to start are XAML controls; bind to a C++/WinRT property and XAML custom
(templated) controls with C++/WinRT.
Important APIs
SyndicationClient::RetrieveFeedAsync method
SyndicationFeed.Items property
winrt::hstring struct
winrt::hresult-error struct
Related topics
C++/CX
Error handling with C++/WinRT
Interop between C++/WinRT and C++/CX
Interop between C++/WinRT and the ABI
Move to C++/WinRT from C++/CX
String handling in C++/WinRT
Feedback
Was this page helpful? Yes No
The aim of this Get Started series is to teach you how to write a desktop program in
C++ using Win32 and COM APIs.
In the first module, you'll learn step-by-step how to create and show a window. Later
modules will introduce the Component Object Model (COM), graphics and text, and
user input.
For this series, it is assumed that you have a good working knowledge of C++
programming. No previous experience with Windows programming is assumed. If you
are new to C++, learning material is available in the C++ language documentation .
In this section
Topic Description
Intro to Win32 This section describes some of the basic terminology and coding
programming in C++ conventions used in Windows programming.
Module 1. Your First In this module, you will create a simple Windows program that
Windows Program shows a blank window.
Module 2. Using COM in This module introduces the Component Object Model (COM),
Your Windows Program which underlies many of the modern Windows APIs.
Module 3. Windows This module introduces the Windows graphics architecture, with a
Graphics focus on Direct2D.
Module 4. User Input This module describes mouse and keyboard input.
Sample Code Contains links to download the sample code for this series.
Feedback
Was this page helpful? ツ Yes ト No
In this set of tutorials, you'll learn how to use DirectX and C++/WinRT to create the basic
Universal Windows Platform (UWP) sample game named Simple3DGameDX. The
gameplay takes place in a simple first-person 3D shooting gallery.
7 Note
The link from which you can download the Simple3DGameDX sample game itself is
Direct3D sample game. The C++/WinRT source code is in the folder named
cppwinrt . For info about other UWP sample apps, see Sample applications for
Windows development.
These tutorials cover all of the major parts of a game, including the processes for
loading assets such as arts and meshes, creating a main game loop, implementing a
simple rendering pipeline, and adding sound and controls.
You'll also see UWP game development techniques and considerations. We'll focus on
key UWP DirectX game development concepts, and call out Windows-Runtime-specific
considerations around those concepts.
Objective
To learn about the basic concepts and components of a UWP DirectX game, and to
become more comfortable designing UWP games with DirectX.
Topic Description
Set up the The first step in developing your game is to set up a project in Microsoft Visual
game project Studio. After you've configured a project specifically for game development, you
could later re-use it as a kind of template.
Define the The first step in coding a Universal Windows Platform (UWP) game is building
game's UWP the framework that lets the app object interact with Windows.
app framework
Game flow Define the high-level state machine to enable player and system interaction.
management Learn how UI interacts with the overall game's state machine and how to create
event handlers for UWP games.
Topic Description
Define the Now, we look at the details of the sample game's main object and how the rules
main game it implements translate into interactions with the game world.
object
Rendering Learn how to develop the rendering pipeline to display graphics. Intro to
framework I: rendering.
Intro to
rendering
Rendering Learn how to assemble the rendering pipeline to display graphics. Game
framework II: rendering, set up and prepare data.
Game
rendering
Add a user Learn how to add a 2D user interface overlay to a DirectX UWP game.
interface
Add controls Now, we take a look at how the sample game implements move-look controls
in a 3-D game, and how to develop basic touch, mouse, and game controller
controls.
Add sound Develop a simple sound engine using XAudio2 APIs to playback game music
and sound effects.
Extend the Learn how to implement a XAML overlay for a UWP DirectX game.
sample game
C/C++ projects and build systems in
Visual Studio
Article • 12/09/2021
You can use Visual Studio to edit, compile, and build any C++ code base with full
IntelliSense support without having to convert that code into a Visual Studio project or
compile with the MSVC toolset. For example, you can edit a cross-platform CMake
project in Visual Studio on a Windows machine, then compile it for Linux using g++ on
a remote Linux machine.
C++ compilation
To build a C++ program means to compile source code from one or more files and then
link those files into an executable file (.exe), a dynamic-load library (.dll) or a static library
(.lib).
The C++ preprocessor transforms all the #directives and macro definitions in each
source file. This creates a translation unit.
The C++ compiler compiles each translation unit into object files (.obj), applying
whatever compiler options have been set.
The linker merges the object files into a single executable, applying the linker
options that have been set.
You can build simple programs by invoking the MSVC compiler (cl.exe) directly from the
command line. The following command accepts a single source code file, and invokes
cl.exe to build an executable called hello.exe:
cl /EHsc hello.cpp
Here the compiler (cl.exe) automatically invokes the C++ preprocessor and the linker to
produce the final output file. For more information, see Building on the command line.
The following list shows various options for Visual Studio Projects - C++:
create a Visual Studio project by using the Visual Studio IDE and configure it by
using property pages. Visual Studio projects produce programs that run on
Windows. For an overview, see Compiling and Building in the Visual Studio
documentation.
open a folder that contains a CMakeLists.txt file. CMake support is integrated into
Visual Studio. You can use the IDE to edit, test, and debug without modifying the
CMake files in any way. This enables you to work in the same CMake project as
others who might be using different editors. CMake is the recommended approach
for cross-platform development. For more information, see CMake projects.
open a loose folder of source files with no project file. Visual Studio will use
heuristics to build the files. This is an easy way to compile and run small console
applications. For more information, see Open Folder projects.
open a folder that contains a makefile, or any other build system configuration file.
You can configure Visual Studio to invoke any arbitrary build commands by adding
JSON files to the folder. For more information, see Open Folder projects.
Open a Windows makefile in Visual Studio. For more information, see NMAKE
Reference.
In This Section
Visual Studio projects
How to create, configure, and build C++ projects in Visual Studio using its native build
system (MSBuild).
CMake projects
How to code, build, and deploy CMake projects in Visual Studio.
Release builds
How to create and troubleshoot optimized release builds for deployment to end users.
The C++ code editor and Visual Studio IDE provide many coding aids. Some are unique
to C++, and some are essentially the same for all Visual Studio languages. For more
information about the shared features, see Writing Code in the Code and Text Editor.
Colorization
Visual Studio colorizes syntax elements to differentiate between types of symbols such
as language keywords, type names, variable names, function parameters, string literals,
and so on.
You can customize the colors by typing "Fonts" in Quick Launch, and then choosing
Fonts and Colors. In the Fonts and Colors dialog, scroll down to the C/C++ options and
then choose a custom font and/or color.
Outlining
Right-click anywhere in a source code file and choose Outlining to collapse or expand
code blocks and/or custom regions to make it easier to browse only the code you're
interested in. For more information, see Outlining.
When you place your cursor in front of a curly brace, '{' or '}', the editor highlights its
matching counterpart.
Other outlining options are located under Edit > Outlining in the main menu.
Line numbers
You can add line numbers to your project by going to Tools > Options > Text Editor >
All Languages > General or by searching for "line num" with Quick Launch (Ctrl + Q).
Line numbers can be set for all languages or for specific languages only, including C++.
To turn on Map Mode, type "map" in the Quick Launch search box in the main toolbar
and choose Use scroll map mode. For more information, see How to: Track your code
by customizing the scrollbar.
When Map Mode is off, the scroll bar still highlights the changes you have made in the
file. Green indicates saved changes and yellow indicates unsaved changes.
If there's an error in your code, you can hover over it, and Quick Info will display the
error message. You can also find the error message in the Error List window.
When you call a function, Parameter Info shows the types of parameters and the order
in which they're expected.
Peek Definition
Hover over a variable or function declaration, right-click, then choose Peek Definition to
see an inline view of its definition without navigating away from your current location.
For more information, see Peek Definition (Alt+F12).
F1 Help
Place the cursor on or just after any type, keyword or function and press F1 to go
directly to the relevant reference topic on Microsoft Learn. F1 also works on items in the
error list and in many dialog boxes.
Class View
Class View displays a searchable set of trees of all code symbols and their scope and
parent/child hierarchies, organized on a per-project basis. You can configure what Class
View displays from Class View Settings (click the gear box icon at the top of the
window).
Generate graph of include files
Right click on a code file in your project and choose Generate graph of include files to
see a graph of which files are included by other files.
A desktop application in C++ is a native application that can access the full set of
Windows APIs, and either runs in a window or in the system console. Desktop
applications in C++ can run on Windows XP through Windows 11 (although Windows
XP is no longer officially supported and there are many new Windows APIs since then).
Any desktop application in C++ can use C Runtime (CRT) and Standard Library classes
and functions, COM objects, and the public Windows functions, which collectively are
known as the Windows API. For an introduction to Windows desktop applications in
C++, see Get Started with Win32 and C++.
There are several broad categories of Windows applications that you can create with
C++, described below. Each has its own programming model and set of Windows-
specific libraries. The C++ standard library and third-party C++ libraries can be used in
any of them.
To get started with traditional Windows C++ programming, see Get Started with
Win32 and C++.
For an example of a traditional C++ desktop application that uses sophisticated
graphics, see Hilo: Developing C++ Applications for Windows.
UWP applications
The Universal Windows Platform (UWP) is the modern Windows API. UWP apps run on
Windows 11, Windows 10, XBox, Windows Phone, Surface Hub, and other devices. UWP
apps use XAML for the user-interface, and are fully touch-enabled. A desktop
application is distinct from a Universal Windows Platform (UWP) app.
For more information about desktop vs. UWP applications, see Choose your
technology.
For more information about UWP, see What's a Universal Windows Platform (UWP)
app and Guide to Windows Universal Apps.
The original C++ support for UWP consisted of C++/CX, a dialect of C++ with syntax
extensions, or the Windows Runtime Library (WRL), which is based on standard C++ and
COM. Both C++/CX and WRL are still supported, but not recommended for new
development.
For new projects, we recommend C++/WinRT, which is entirely based on standard C++
and provides faster performance.
A C++/CLI application or component uses extensions to C++ syntax (as allowed by the
C++ Standard) to enable interaction between .NET and native C++code. A C++/CLI
application can have parts that run natively and parts that run on the .NET Framework
with access to the .NET Base Class Library. C++/CLI is the preferred option when you
have native C++ code that needs to work with code written in C# or Visual Basic. It's
intended for use in .NET DLLs rather than in user interface code.
For more information, see .NET Programming with C++/CLI (Visual C++).
Desktop Bridge
In Windows 10 and later, you can package your existing desktop application or COM
object as a UWP app. It can use UWP features such as touch, or call APIs from the
modern Windows API set. You can also add a UWP app to a desktop solution in Visual
Studio, package them together in a single package, and use Windows APIs to
communicate between them.
Visual Studio 2017 version 15.4 and later lets you create a Windows Application Package
Project to greatly simplify the work of packaging your existing desktop application. A
few restrictions apply to the registry calls or APIs your desktop application can use.
However, in many cases you can create alternate code paths to achieve similar
functionality while running in an app package.
C++ or .NET?
In general, .NET programming in C# is less complex, less error-prone, and has a more
modern object-oriented API than Win32 or MFC. In most cases, its performance is more
than adequate.
.NET features the Windows Presentation Foundation (WPF) for rich graphics, and you
can consume both Win32 and the modern Windows Runtime API. As a general rule, we
recommend using C++ for desktop applications when you require:
It's also possible to combine the power and efficiency of C++ with .NET programming.
You can create a user interface in C# and use C++/CLI to enable the application to
consume native C++ libraries.
Games
DirectX games can run on the PC or Xbox.
Windows services
A Windows service is a program that can run in the background with little or no user
interaction. These programs are called daemons on UNIX systems.
COM
The Component Object Model (COM) is a specification that enables programs written in
different languages to interoperate with one another.
Many Windows components are implemented as COM objects and follow standard
COM rules for object creation, interface discovery, and object destruction. Using COM
objects from C++ desktop applications is relatively straightforward, but writing your
own COM object is more advanced.
The Active Template Library (ATL) provides macros and helper functions that simplify
COM development. For more information, see ATL COM desktop components.
MFC
An MFC application is a Windows desktop application that uses the Microsoft
Foundation Classes to create the user interface. An MFC application can also use COM
components and CRT and Standard Library APIs.
MFC provides a thin C++ object-oriented wrapper over the window message loop and
Windows APIs. MFC is the default choice for applications—especially enterprise-type
applications—that have many user interface controls or custom user controls.
MFC provides convenient helper classes for window management, serialization, text
manipulation, printing, and modern user interface elements such as the ribbon. To be
effective with MFC, you should be familiar with Win32.
header files are found in the Windows SDK installation folder (for example, C:\Program
Files (x86)\Windows Kits\10\Include\10.0.22621.0\ucrt\ )
The vcpkg package manager lets you conveniently install hundreds of third-party open-
source libraries for Windows. For more information, see vcpkg.
Active Template Library (ATL): A powerful helper library for creating COM
components. For more information, see ATL COM Desktop Components.
C++ AMP (C++ Accelerated Massive Parallelism): A library that enables high-
performance general computational work on the GPU. For more information, see
C++ AMP (C++ Accelerated Massive Parallelism).
Many Windows programming scenarios also require the Windows SDK, which includes
the header files that enable access to the Windows operating system components. By
default, Visual Studio installs the Windows SDK as a component of the C++ Desktop
workload, which enables development of Universal Windows apps. To develop UWP
apps, you need a Windows 10 or later version of the Windows SDK.
The default location for all versions of the Windows SDK that you install is: Program
Files (x86)\Windows Kits .
Development Tools
Visual Studio includes a powerful debugger for native code, static analysis tools,
graphics debugging tools, a full-featured code editor, support for unit tests, and many
other tools and utilities.
For more information, see Get started developing with Visual Studio, and Overview
of C++ development in Visual Studio.
In this section
ノ Expand table
Link Description
How to: Use the Windows Contains steps for setting up your project to build using the
SDK in a Windows desktop Windows SDK.
application
Walkthrough: Create a Create a simple Windows console application. A Win32 (or Win64)
console calculator in C++ console application has no window of its own and no message loop.
It runs in the console window, and input and output are handled
through the command line.
Windows Desktop Wizard Use the wizard to create new Windows projects.
Active Template Library Use the ATL library to create COM components in C++.
(ATL)
ATL and MFC Shared Use classes such as CString that are shared in ATL and MFC.
classes
Microsoft Foundation Use MFC to create large or small Windows applications with dialogs
Classes (MFC) and controls
Working with resource How to add images, icons, string tables, and other resources to a
files desktop application.
Related Articles
ノ Expand table
Title Description
Windows Contains information about the Windows API and COM. (Some Windows
development APIs and third-party DLLs are implemented as COM objects.)
Hilo: Developing Describes how to create a rich-client Windows desktop application that
C++ applications for uses Windows Animation and Direct2D to create a carousel-based user
Windows 7 interface. This tutorial hasn't been updated since Windows 7, but still
provides a thorough introduction to Win32 programming.
.NET development Create wrappers for native C++ libraries that enable it to communication
with C++/CLI with .NET applications and components.
Universal Windows Write UWP applications using C++/CX or Windows Runtime Template
apps (C++) Library (WRL).
C++ attributes for Nonstandard attributes for Windows-only programming using .NET or
COM and .NET COM.
See also
C++ in Visual Studio
Feedback
Was this page helpful? Yes No
The Universal Windows Platform (UWP) is the modern programming interface for
Windows. With UWP you write an application or component once and deploy it on any
Windows 10 or later device. You can write a component in C++ and applications written
in any other UWP-compatible language can use it.
Most of the UWP documentation is in the Windows content tree at Universal Windows
Platform documentation. There you will find beginning tutorials as well as reference
documentation.
For new UWP apps and components, we recommend that you use C++/WinRT, a new
standard C++17 language projection for Windows Runtime APIs. C++/WinRT is
available in the Windows SDK from version 1803 (10.0.17134.0) onward. C++/WinRT is
implemented entirely in header files, and is designed to provide you with first-class
access to the modern Windows API. Unlike the C++/CX implementation, C++/WinRT
doesn't use non-standard syntax or Microsoft language extensions, and it takes full
advantage of the C++ compiler to create highly-optimized output. For more
information, see Introduction to C++/WinRT.
You can use the Desktop Bridge app converter to package your existing desktop
application for deployment through the Microsoft Store. For more information, see
Using Visual C++ Runtime in Centennial project and Desktop Bridge.
See also
C++ in Visual Studio
Overview of Windows Programming in C++
Game Development with C++
Article • 10/06/2021
When you create a Universal Windows Platform (UWP) game, you have the opportunity
to reach millions of players worldwide across phone, PC, and Xbox One. With Xbox on
Windows, Xbox Live, cross-device multiplayer, an amazing gaming community, and
powerful new features like the Universal Windows Platform (UWP) and DirectX 12,
Windows games thrill players of all ages and genres. The new Universal Windows
Platform (UWP) delivers compatibility for your game across Windows devices with a
common API for phone, PC, and Xbox One, along with tools and options to tailor your
game to each device experience.
b GET STARTED
c HOW-TO GUIDE
i REFERENCE
ConnectionManager reference
f QUICKSTART
i REFERENCE
f QUICKSTART
b GET STARTED
e OVERVIEW
g TUTORIAL
d TRAINING
Cross-platform reference
i REFERENCE
In Visual Studio 2022, the default target framework for .NET Core projects is 6.0. For
.NET Frameworks projects, the default is 4.7.2. The .NET Framework version selector is on
the Configure your new project page of the Create a new project dialog.
In this section
C++/CLI tasks
Serialization (C++/CLI)
Reflection (C++/CLI)
Strong Name assemblies (assembly signing) (C++/CLI)
Exceptions in C++/CLI
Boxing (C++/CLI)
See also
Native and .NET interoperability
Cloud and Web Programming in Visual
C++
Article • 09/21/2021
In C++, you have several options for connecting to the web and the cloud.
The Azure Storage Client Library for C++ provides a comprehensive API for
working with Azure storage, including but not limited to the following abilities:
Create, read, delete, and list blob containers, tables, and queues.
Create, read, delete, list and copy blobs plus read and write blob ranges.
Insert, delete, replace, merge, and query entities in an Azure table.
Enqueue and dequeue messages in an Azure queue.
Lazily list containers, blobs, tables, and queues, and lazily query entities
The ANSI C99 Azure IoT Hub SDKs for Internet of Things enable IoT applications to
run on the device or on the backend.
The OneDrive API provides a set of HTTP services to connect your application to
files and folders in Microsoft 365 and SharePoint Server 2016.
A Windows Runtime HTTP client class modeled on the .NET Framework class of the
same name in the System.Web namespace. HttpClient fully supports
asynchronous upload and download over HTTP, and pipeline filters that enable the
insertion of custom HTTP handlers into the pipeline. The Windows SDK includes
sample filters for metered networks, OAuth authentication, and more. For apps
that target only Universal Windows Platform, we recommend that you use the
Windows::Web:HttpClient class.
IXMLHTTPRequest2 interface
Provides a native COM interface that you can use in Windows Runtime apps or
Windows desktop apps to connect to the Internet over HTTP and issue GET, PUT,
and other HTTP commands. For more information, see Walkthrough: Connecting
Using Tasks and XML HTTP Requests.
Windows API that you can use in Windows desktop apps to connect to the
Internet.
See also
C++ in Visual Studio
Microsoft Azure C and C++ Developer Center
Networks and web services (UWP)
Microsoft C++ porting and upgrading
guide
Article • 10/25/2021
This article provides a guide for upgrading Microsoft C++ code to the latest version of
Visual Studio. For projects created in Visual Studio 2010 through 2017, just open the
project in Visual Studio 2019. You can upgrade a Visual Studio 2008 or earlier project in
two steps. Use Visual Studio 2010 to convert the project to MSBuild format first. Then
open the project in Visual Studio 2019. For complete instructions, see Upgrading C++
projects from earlier versions of Visual Studio.
The toolsets in Visual Studio 2015, Visual Studio 2017, and Visual Studio 2019 are
binary-compatible. Now you can upgrade to a more recent version of the compiler
without having to upgrade your library dependencies. For more information, see C++
binary compatibility between Visual Studio versions.
When upgrading projects that use open-source libraries or are meant to run on multiple
platforms, we recommended migrating to a CMake-based project. For more
information, see CMake projects in Visual Studio
The same code can run faster, because we've improved compiler optimizations.
Modern C++ features and programming practices eliminate many common causes
of bugs, and produce code that's far easier to maintain than older C-style idioms.
Build times are faster, because of performance improvements in the compiler and
linker.
Better standards conformance. The /permissive- compiler option helps you identify
code that doesn't conform to the current C++ standard. The new preprocessor
supports code conformance, too.
Better run-time security, including more secure C Runtime library features. And,
compiler features such as guard checking and address sanitizers (new in Visual
Studio 2019 version 16.4).
modern static analysis tools, including the C++ Core Guidelines checkers and
Clang-Tidy, to help identify potential problems in your source code.
automatic formatting according to your choice of modern styles can help make
legacy code much more readable.
For more information, see Use native multi-targeting in Visual Studio to build old
projects.
In this section
Title Description
Upgrading How to upgrade your code base to the latest version of Visual Studio and the
C++ projects compiler.
from earlier
versions of
Visual Studio
IDE tools for Useful IDE features that help in the upgrade process.
upgrading
C++ code
C++ binary Consume v140 and later libraries as-is from v140 and later projects.
compatibility
between
Visual Studio
versions
Use native Use Visual Studio with older compilers and libraries.
multi-
targeting in
Visual Studio
to build old
projects
Title Description
Visual C++ A list of all the changes in the Microsoft C++ libraries and build tools from Visual
change Studio 2003 through 2015 that might require changes in your code.
history 2003 -
2015
Visual C++ All the "what's new" information for Microsoft C++ from Visual Studio 2003
What's New through Visual Studio 2015.
2003 through
2015
Porting and For this section, we ported and upgrades several samples and applications and
Upgrading: discussed the experiences and results. These articles give you a sense of what's
Examples and involved in the porting and upgrading process. Throughout the process, we
Case Studies discuss tips and tricks for upgrading and show how specific errors were fixed.
Porting to the Contains information about porting app code to Windows 10 and later
Universal
Windows
Platform
Introduction Provides information for UNIX users who are new to Visual C++ and want to
to Visual C++ become productive with it.
for UNIX
Users
See also
C++ in Visual Studio
What's New for The C++ compiler in Visual Studio
C++ conformance improvements in Visual Studio
Security Best Practices for C++
Article • 08/03/2021
This article contains information about security tools and practices. Using them does not
make applications immune from attack, but it makes successful attacks less likely.
Security-Enhanced CRT
The C Runtime Library (CRT) has been augmented to include secure versions of
functions that pose security risks—for example, the unchecked strcpy string copy
function. Because the older, nonsecure versions of these functions are deprecated, they
cause compile-time warnings. We encourage you to use the secure versions of these
CRT functions instead of suppressing the compilation warnings. For more information,
see Security Features in the CRT.
SafeInt Library
SafeInt Library helps prevent integer overflows and other exploitable errors that might
occur when the application performs mathematical operations. The SafeInt library
includes the SafeInt Class, the SafeIntException Class, and several SafeInt Functions.
The SafeInt class protects against integer overflow and divide-by-zero exploits. You can
use it to handle comparisons between values of different types. It provides two error
handling policies. The default policy is for the SafeInt class to throw a
SafeIntException class exception to report why a mathematical operation cannot be
completed. The second policy is for the SafeInt class to stop program execution. You
can also define a custom policy.
Each SafeInt function protects one mathematical operation from an exploitable error.
You can use two different kinds of parameters without converting them to the same
type. To protect multiple mathematical operations, use the SafeInt class.
Checked Iterators
A checked iterator enforces container boundaries. By default, when a checked iterator is
out of bounds, it generates an exception and ends program execution. A checked
iterator provides other levels of response that depend on values that are assigned to
preprocessor defines such as _SECURE_SCL_THROWS and _ITERATOR_DEBUG_LEVEL . For
example, at _ITERATOR_DEBUG_LEVEL=2 , a checked iterator provides comprehensive
correctness checks in debug mode, which are made available by using asserts. For more
information, see Checked Iterators and _ITERATOR_DEBUG_LEVEL.
Localization
Naming conventions
Performance
Security
The AppVerifier monitors how an application uses the operating system. It watches the
file system, registry, memory, and APIs while the application is running, and
recommends source-code fixes for issues that it uncovers.
Test for potential application compatibility errors that are caused by common
programming mistakes.
This topic explains how configuring Windows user accounts as a member of the Users
Group (as opposed to the Administrators Group) increases security by reducing the
chances of being infected with malicious code.
Security Risks
Running as an administrator makes your system vulnerable to several kinds of security
attack, such as "Trojan horse" and "buffer overrun." Merely visiting an Internet site as an
administrator can be damaging to the system, as malicious code that is downloaded
from an Internet site may attack your computer. If successful, it inherits your
administrator permissions and can then perform actions such as deleting all your files,
reformatting your hard drive, and creating a new user accounts with administrative
access.
Writing to protected areas of the file system, such as the Windows or Program
Files directories
Debugging
You can debug any applications that you launch within Visual Studio (native and
unmanaged) as a non-administrator by becoming part of the Debugging Group. This
includes the ability to attach to a running application using the Attach to Process
command. However, it is necessary to be part of the Administrator Group in order to
debug native or managed applications that were launched by a different user.
See also
Security Best Practices
How User Account Control (UAC)
Affects Your Application
Article • 08/03/2021
User Account Control (UAC) is a feature of Windows Vista in which user accounts have
limited privileges. You can find detailed information about UAC at these sites:
The first option is to modify the UAC fragment of the manifest to change the execution
level to requireAdministrator. The application will then prompt the user for
administrative credentials before it runs. For information about how to do this, see
/MANIFESTUAC (Embeds UAC information in manifest).
The second option is to not embed a UAC fragment into the manifest by specifying the
/MANIFESTUAC:NO linker option. In this case, your application will run virtualized. Any
changes you make to the registry or to the file system will not persist after your
application has ended.
The following flowchart describes how your application will run depending on whether
UAC is enabled and whether the application has a UAC manifest:
See also
Security Best Practices
C++ Developer Guidance for
Speculative Execution Side Channels
Article • 08/03/2021
This article contains guidance for developers to assist with identifying and mitigating
speculative execution side channel hardware vulnerabilities in C++ software. These
vulnerabilities can disclose sensitive information across trust boundaries and can affect
software that runs on processors that support speculative, out-of-order execution of
instructions. This class of vulnerabilities was first described in January, 2018 and
additional background and guidance can be found in Microsoft's security advisory .
While speculative execution does not affect the architecturally visible state, it can leave
residual traces in non-architectural state, such as the various caches that are used by the
CPU. It is these residual traces of speculative execution that can give rise to side channel
vulnerabilities. To better understand this, consider the following code fragment which
provides an example of CVE-2017-5753 (Bounds Check Bypass):
C++
In this example, ReadByte is supplied a buffer, a buffer size, and an index into that
buffer. The index parameter, as specified by untrusted_index , is supplied by a less
privileged context, such as a non-administrative process. If untrusted_index is less than
buffer_size , then the character at that index is read from buffer and used to index into
a shared region of memory referred to by shared_buffer .
CPU may speculatively read a byte from beyond the bounds of buffer (which could be
a secret) and could then use that byte value to compute the address of a subsequent
load through shared_buffer .
While the CPU will eventually detect this misprediction, residual side effects may be left
in the CPU cache that reveal information about the byte value that was read out of
bounds from buffer . These side effects can be detected by a less privileged context
running on the system by probing how quickly each cache line in shared_buffer is
accessed. The steps that can be taken to accomplish this are:
2. Flush all cache lines in shared_buffer . The attacking context must flush all of the
cache lines in the shared region of memory referred to by shared_buffer . Since the
memory region is shared, this is straightforward and can be accomplished using
intrinsics such as _mm_clflush .
bounds, thus causing the respective cache line to be loaded by the CPU.
4. Read each cache line in shared_buffer to see which is accessed most quickly. The
attacking context can read each cache line in shared_buffer and detect the cache
line that loads significantly faster than the others. This is the cache line that is likely
to have been brought in by step 3. Since there is a 1:1 relationship between byte
value and cache line in this example, this allows the attacker to infer the actual
value of the byte that was read out-of-bounds.
Trust Description
boundary
Virtual Applications that isolate workloads in separate virtual machines that receive
machine untrusted data from another virtual machine may be at risk.
boundary
Kernel A kernel-mode device driver that receives untrusted data from a non-administrative
boundary user mode process may be at risk.
Process An application that receives untrusted data from another process running on the
boundary local system, such as through a Remote Procedure Call (RPC), shared memory, or
other Inter-Process Communication (IPC) mechanisms may be at risk.
Enclave An application that executes within a secure enclave (such as Intel SGX) that receives
boundary untrusted data from outside of the enclave may be at risk.
Language An application that interprets or Just-In-Time (JIT) compiles and executes untrusted
boundary code written in a higher-level language may be at risk.
Applications that have attack surface exposed to any of the above trust boundaries
should review code on the attack surface to identify and mitigate possible instances of
speculative execution side channel vulnerabilities. It should be noted that trust
boundaries exposed to remote attack surfaces, such as remote network protocols, have
not been demonstrated to be at risk to speculative execution side channel
vulnerabilities.
For each example, a comment with the phrase "SPECULATION BARRIER" is inserted
where a developer could introduce a barrier as a mitigation. This is discussed in more
detail in the section on mitigations.
C++
Similarly, an array out-of-bounds load may occur in conjunction with a loop that
exceeds its terminating condition due to a misprediction. In this example, the
conditional branch associated with the x < buffer_size expression may mispredict and
speculatively execute the body of the for loop when x is greater than or equal to
buffer_size , thus resulting in a speculative out-of-bounds load.
C++
the corresponding branch target. This code is safe architecturally, but if the CPU
mispredicts the conditional branch, it could result in DispatchTable being indexed by
untrusted_message_id when its value is greater than or equal to MAX_MESSAGE_ID , thus
C++
#define MAX_MESSAGE_ID 16
As with the case of an array out-of-bounds load feeding another load, this condition
may also arise in conjunction with a loop that exceeds its terminating condition due to a
misprediction.
Array out-of-bounds store feeding an indirect branch
While the previous example showed how a speculative out-of-bounds load can
influence an indirect branch target, it is also possible for an out-of-bounds store to
modify an indirect branch target, such as a function pointer or a return address. This can
potentially lead to speculative execution from an attacker-specified address.
C++
Similarly, if a function pointer local variable named func were allocated on the stack,
then it may be possible to speculatively modify the address that func refers to when the
conditional branch misprediction occurs. This could result in speculative execution from
an arbitrary address when the function pointer is called through.
C++
For speculative store bypass, this could occur in scenarios where a compiler reuses a
stack location for variables of multiple types. This is because the architectural store of a
variable of type A may be bypassed, thus allowing the load of type A to speculatively
execute before the variable is assigned. If the previously stored variable is of a different
type, then this can create the conditions for a speculative type confusion.
For conditional branch misprediction, the following code snippet will be used to
describe different conditions that speculative type confusion can give rise to.
C++
enum TypeName {
Type1,
Type2
};
class CBaseType {
public:
CBaseType(TypeName type) : type(type) {}
TypeName type;
};
obj2->dispatch_routine();
return obj2->field2;
}
}
load of data that may be secret. This value is then used in a load from shared_buffer
which can create observable side effects, as with the array out-of-bounds example
described previously.
index . If this occurs, an uninitialized value for index will be used as the offset into
buffer which could enable an attacker to read sensitive information out-of-bounds and
convey this through a side channel through the dependent load of shared_buffer .
C++
// SPECULATION BARRIER
unsigned char value = buffer[index];
return shared_buffer[value * 4096];
}
of the indirect branch. However, depending on the code produced by the compiler, a
speculative store bypass may occur that allows the indirect branch through routine to
be speculatively executed ahead of the assignment to routine . If this occurs, an attacker
may be able to speculatively execute from an arbitrary address, assuming the attacker
can influence or control the uninitialized value of routine .
C++
#define MAX_MESSAGE_ID 16
// SPECULATION BARRIER
routine(buffer, buffer_size);
}
Mitigation options
Speculative execution side channel vulnerabilities can be mitigated by making changes
to source code. These changes can involve mitigating specific instances of a
vulnerability, such as by adding a speculation barrier, or by making changes to the
design of an application to make sensitive information inaccessible to speculative
execution.
Architecture Speculation barrier intrinsic for CVE- Speculation barrier intrinsic for CVE-
2017-5753 2018-3639
For example, the following code pattern can be mitigated by using the _mm_lfence
intrinsic as shown below.
C++
It should be noted that the index masking performed here could be subject to
speculative store bypass depending on the code that is generated by the compiler.
C++
See also
Guidance to mitigate speculative execution side-channel vulnerabilities
Mitigating speculative execution side channel hardware vulnerabilities
C/C++ language and standard libraries
reference
Article • 09/12/2024
This section of the documentation contains reference content for the Microsoft
implementation of the ISO standard C and C++ languages. The language reference
includes documentation for the preprocessor, compiler intrinsics, and supported
assembly languages.
You'll also find documentation for the C runtime library, the C++ standard library, and
several other libraries available with the Microsoft C/C++ compiler (MSVC) here.
Language reference
C language
Reference content for the Microsoft implementation of the C language.
C++ language
Reference content for the Microsoft implementation of the C++ language.
C/C++ preprocessor
Reference content for the preprocessor used by C and C++.
Compiler intrinsics
Describes intrinsic functions that are available in Microsoft C and C++ for x86, ARM,
ARM64, and x64 architectures.
Inline assembler
Explains how to use the Visual C/C++ inline assembler with x86 processors.
Libraries reference
Standard libraries
C runtime library
The reference for the Microsoft implementation of the C runtime library (CRT),
sometimes referred to as the Universal CRT.
Additional libraries
C++ AMP (C++ Accelerated Massive Parallelism)
Classes that enable the use of modern graphics processors for general purpose
programming.
Concurrency Runtime
Classes that simplify the writing of programs that use data parallelism or task
parallelism.
OpenMP
Reference for the Microsoft implementation of the OpenMP API.
Proxy library
A header-only C++20 library for using polymorphism in C++ without inheritance. For
API reference information, see Proxy 3 Specifications
SafeInt library
A portable library that can be used with MSVC, GCC, or Clang to help prevent integer
overflows.
Data Access Libraries Libraries to support data access using ATL or MFC, and legacy
services such as OLE DB and ODBC.
Related articles
Windows Runtime (WinRT) with C++
C++/WinRT is an entirely standard modern C++17 language projection for Windows
Runtime (WinRT) APIs, implemented as a header-file-based library.
Windows Runtime C++ Template Library (WRL)
A legacy template library for the Windows Runtime, replaced by C++/WinRT.
Feedback
Was this page helpful? Yes No
C Language
C++ Language
C/C++ Preprocessor
Compiler Intrinsics and Assembly Language
C Language Reference
Article • 08/03/2021
Preprocessor Reference
Compiler and linker options are documented in the C/C++ Building Reference.
See also
C++ Language Reference
C++ Language Reference
Article • 08/03/2021
For an overview of Modern C++ programming practices, see Welcome Back to C++.
C++ Keywords
C++ Operators
In This Section
Lexical Conventions
Fundamental lexical elements of a C++ program: tokens, comments, operators,
keywords, punctuators, literals. Also, file translation, operator precedence/associativity.
Basic Concepts
Scope, linkage, program startup and termination, storage classes, and types.
Built-in types The fundamental types that are built into the C++ compiler and their
value ranges.
Standard Conversions
Type conversions between built-in types. Also, arithmetic conversions and conversions
among pointer, reference, and pointer-to-member types.
Declarations and definitions Declaring and defining variables, types and functions.
Expressions
Types of expressions, semantics of expressions, reference topics on operators, casting
and casting operators, run-time type information.
Lambda Expressions
A programming technique that implicitly defines a function object class and constructs a
function object of that class type.
Statements
Expression, null, compound, selection, iteration, jump, and declaration statements.
Unions
User-defined types in which all members share the same memory location.
Derived Classes
Single and multiple inheritance, virtual functions, multiple base classes, abstract
classes, scope rules. Also, the __super and __interface keywords.
Member-Access Control
Controlling access to class members: public , private , and protected keywords. Friend
functions and classes.
Overloading
Overloaded operators, rules for operator overloading.
Exception Handling
C++ exception handling, structured exception handling (SEH), keywords used in writing
exception handling statements.
Templates
Template specifications, function templates, class templates, typename keyword,
templates vs. macros, templates and smart pointers.
Event Handling
Declaring events and event handlers.
Microsoft-Specific Modifiers
Modifiers specific to Microsoft C++. Memory addressing, calling conventions, naked
functions, extended storage-class attributes ( __declspec ), __w64 .
Inline Assembler
Using assembly language and C++ in __asm blocks.
Microsoft Extensions
Microsoft extensions to C++.
Nonstandard Behavior
Information about nonstandard behavior of the Microsoft C++ compiler.
Related Sections
Component Extensions for Runtime Platforms
Reference material on using the Microsoft C++ compiler to target .NET.
See also
C Language Reference
C/C++ preprocessor reference
Article • 08/03/2021
In Visual Studio 2019 the /Zc:preprocessor compiler option provides a fully conformant
C11 and C17 preprocessor. This is the default when you use the compiler flag /std:c11
or /std:c17 .
In this section
Preprocessor
Provides an overview of the traditional and new conforming preprocessors.
Preprocessor directives
Describes directives, typically used to make source programs easy to change and easy to
compile in different execution environments.
Preprocessor operators
Discusses the four preprocessor-specific operators used in the context of the #define
directive.
Predefined macros
Discusses predefined macros as specified by the C and C++ standards and by Microsoft
C++.
Pragmas
Discusses pragmas, which offer a way for each compiler to offer machine- and operating
system-specific features while retaining overall compatibility with the C and C++
languages.
Related sections
C++ language reference
Provides reference material for the Microsoft implementation of the C++ language.
C language reference
Provides reference material for the Microsoft implementation of the C language.
This section of the documentation contains information about compiler intrinsics and
the assembly language.
Related articles
Title Description
Compiler intrinsics Describes intrinsic functions that are available in Microsoft C and C++
for x86, ARM, and x64 architectures.
Inline assembler Explains how to use the Visual C/C++ inline assembler with x86
processors.
ARM assembler Provides reference material for the Microsoft ARM assembler (armasm)
reference and related tools.
Microsoft Macro Provides reference material for the Microsoft Macro assembler (masm).
Assembler reference
C++ in Visual Studio The top-level article for Visual C++ documentation.
Compiler intrinsics
Article • 08/03/2021
Most functions are contained in libraries, but some functions are built in (that is,
intrinsic) to the compiler. These are referred to as intrinsic functions or intrinsics.
Remarks
If a function is an intrinsic, the code for that function is usually inserted inline, avoiding
the overhead of a function call and allowing highly efficient machine instructions to be
emitted for that function. An intrinsic is often faster than the equivalent inline assembly,
because the optimizer has a built-in knowledge of how many intrinsics behave, so some
optimizations can be available that are not available when inline assembly is used. Also,
the optimizer can expand the intrinsic differently, align buffers differently, or make other
adjustments depending on the context and arguments of the call.
The use of intrinsics affects the portability of code, because intrinsics that are available
in Visual C++ might not be available if the code is compiled with other compilers and
some intrinsics that might be available for some target architectures are not available
for all architectures. However, intrinsics are usually more portable than inline assembly.
The intrinsics are required on 64-bit architectures where inline assembly is not
supported.
Some intrinsics are available only as intrinsics, and some are available both in function
and intrinsic implementations. You can instruct the compiler to use the intrinsic
implementation in one of two ways, depending on whether you want to enable only
specific functions or you want to enable all intrinsics. The first way is to use #pragma
intrinsic( intrinsic-function-name-list ) . The pragma can be used to specify a single
intrinsic or multiple intrinsics separated by commas. The second is to use the /Oi
(Generate intrinsic functions) compiler option, which makes all intrinsics on a given
platform available. Under /Oi, use #pragma function( intrinsic-function-name-list ) to
force a function call to be used instead of an intrinsic. If the documentation for a specific
intrinsic notes that the routine is only available as an intrinsic, then the intrinsic
implementation is used regardless of whether /Oi or #pragma intrinsic is specified. In
all cases, /Oi or #pragma intrinsic allows, but does not force, the optimizer to use the
intrinsic. The optimizer can still call the function.
Some standard C/C++ library functions are available in intrinsic implementations on
some architectures. When calling a CRT function, the intrinsic implementation is used if
/Oi is specified on the command line.
A header file, <intrin.h>, is available that declares prototypes for the common intrinsic
functions. Manufacturer-specific intrinsics are available in the <immintrin.h> and
<ammintrin.h> header files. Additionally, certain Windows headers declare functions
that map onto a compiler intrinsic.
The following sections list all intrinsics that are available on various architectures. For
more information on how the intrinsics work on your particular target processor, refer to
the manufacturer's reference documentation.
ARM intrinsics
ARM64 intrinsics
See also
ARM assembler reference
Microsoft Macro Assembler reference
Keywords
C run-time library reference
ARM Assembler reference
Article • 05/10/2022
The articles in this section of the documentation provide reference material for the
Microsoft ARM assembler (armasm or armasm64) and related tools.
Related articles
Title Description
ARM Assembler Describes commonly seen armasm and armasm64 warning and error
diagnostic messages messages.
ARM Assembler Describes the ARM directives that are different in Microsoft armasm
directives and armasm64.
ARM Architecture Choose the relevant manual for your ARM architecture. Each contains
Reference Manual on reference sections about ARM, Thumb, NEON, and VFP, and additional
the ARM Developer information about the ARM assembly language.
website.
ARM Compiler armasm Choose a recent version to find up-to-date information about the
User Guide on the ARM assembly language.
ARM Developer website.
) Important
The armasm assembler that the ARM Developer website describes isn't the same as
the Microsoft armasm assembler that's included in Visual Studio and is
documented in this section.
See also
ARM intrinsics
ARM64 intrinsics
Compiler intrinsics
Inline Assembler
Article • 08/03/2021
Microsoft Specific
Assembly language serves many purposes, such as improving program speed, reducing
memory needs, and controlling hardware. You can use the inline assembler to embed
assembly-language instructions directly in your C and C++ source programs without
extra assembly and link steps. The inline assembler is built into the compiler, so you
don't need a separate assembler such as the Microsoft Macro Assembler (MASM).
7 Note
Programs with inline assembler code are not fully portable to other hardware
platforms. If you are designing for portability, avoid using inline assembler.
Inline assembly is not supported on the ARM and x64 processors. The following topics
explain how to use the Visual C/C++ inline assembler with x86 processors:
__asm
The Microsoft Macro Assembler (MASM) provides several advantages over inline
assembly. MASM contains a macro language that has features such as looping,
arithmetic, and text string processing. MASM gives you greater control over the
hardware. By using MASM, you also can reduce time and memory overhead in your
code.
In This Section
ML and ML64 command-line option
Describes the ML and ML64 command-line options.
Instruction Format
Describes basic instruction format and instruction prefixes for MASM.
Directives reference
Provides links to articles that discuss the use of directives in MASM.
Symbols Reference
Provides links to articles that discuss the use of symbols in MASM.
Operators Reference
Provides links to articles that discuss the use of operators in MASM.
ML error messages
Describes fatal and nonfatal error messages and warnings.
Related Sections
C++ in Visual Studio
Provides links to different areas of the Visual Studio and Visual C++ documentation.
See also
Compiler Intrinsics
x86 Intrinsics
x64 (amd64) Intrinsics
Component Extensions for .NET and
UWP
Article • 09/21/2021
The C++ standard allows compiler vendors to provide non-standard extensions to the
language. Microsoft provides extensions to help you connect native C++ code to code
that runs on the .NET Framework or the Universal Windows Platform (UWP). The .NET
extensions are called C++/CLI and produce code that executes in the .NET managed
execution environment that is called the Common Language Runtime (CLR). The UWP
extensions are called C++/CX and they produce native machine code.
7 Note
The C++/CX extensions are a subset of C++/CLI. Although the extension syntax is
identical in most cases, the code that is generated depends on whether you specify the
/ZW compiler option to target UWP, or the /clr option to target .NET. These switches
are set automatically when you use Visual Studio to create a project.
ref struct
value struct
interface
struct
Override Specifiers
You can use the following keywords to qualify override behavior for derivation. Although
the new keyword is not an extension of C++, it is listed here because it can be used in
an additional context. Some specifiers are also valid for native programming. For more
information, see How to: Declare Override Specifiers in Native Compilations (C++/CLI).
sealed Yes Prevents classes from being used as base classes. sealed
where Yes Specifies the constraints that are applied to a generic type
parameter.
Miscellaneous Keywords
The following keywords have been added to the C++ extensions.
ref new Yes Allocates a Windows Runtime type. Use instead of new ref new,
and delete . gcnew
Template Constructs
The following language constructs are implemented as templates, instead of as
keywords. If you specify the /ZW compiler option, they are defined in the lang
namespace. If you specify the /clr compiler option, they are defined in the cli
namespace.
pin_ptr (CLR only) Points to CLR reference types to temporarily suppress pin_ptr
the garbage-collection system. (C++/CLI)
safe_cast Determines and executes the optimal casting method for a safe_cast
runtime type.
typeid (CLR only) Retrieves a System.Type object that describes the given typeid
type or object.
Declarators
The following type declarators instruct the runtime to automatically manage the lifetime
and deletion of allocated objects.
Topic Description
__identifier (C++/CLI) (Windows Runtime and CLR) Enables the use of keywords as
identifiers.
Variable Argument Lists (...) (Windows Runtime and CLR) Enables a function to take a variable
(C++/CLI) number of arguments.
.NET Framework Equivalents Lists the CLR types that are used in place of C++ integral types.
to C++ Native Types
(C++/CLI)
appdomain __declspec __declspec modifier that mandates that static and global
modifier variables exist per appdomain.
C-Style Casts with /clr Describes how C-style casts are interpreted.
(C++/CLI)
Friend Assemblies (C++) Discusses how a client assembly can access all types in an
assembly component.
Compiler Support for Type Discusses how to detect characteristics of types at compile time.
Traits
managed, unmanaged Demonstrates how managed and unmanaged functions can co-
pragmas exist in the same module.
process __declspec modifier __declspec modifier that mandates that static and global
variables exist per process.
See also
.NET Programming with C++/CLI (Visual C++)
Native and .NET Interoperability
C++ Attributes for COM and .NET
Article • 02/07/2023
Microsoft defines a set of C++ attributes that simplify COM programming and .NET
Framework common language runtime development. When you include attributes in
your source files, the compiler works with provider DLLs to insert code or modify the
code in the generated object files. These attributes aid in the creation of .idl files,
interfaces, type libraries, and other COM elements. In the integrated development
environment (IDE), attributes are supported by the wizards and by the Properties
window.
While attributes eliminate some of the detailed coding needed to write COM objects,
you need a background in COM fundamentals to best use them.
7 Note
Purpose of Attributes
Attributes extend C++ in directions not currently possible without breaking the classic
structure of the language. Attributes allow providers (separate DLLs) to extend language
functionality dynamically. The primary goal of attributes is to simplify the authoring of
COM components, in addition to increasing the productivity level of the component
developer. Attributes can be applied to nearly any C++ construct, such as classes, data
members, or member functions. The following is a highlight of benefits provided by this
new technology:
Replaces the large amount of IDL code required by a COM component with a few
concise attributes.
For example, to implement a simple event sink for a generic ATL class, you could apply
the event_receiver attribute to a specific class such as CMyReceiver . The event_receiver
attribute is then compiled by the Microsoft C++ compiler, which inserts the proper code
into the object file.
C++
[event_receiver(com)]
class CMyReceiver
{
void handler1(int i) { ... }
void handler2(int i, float j) { ... }
}
You can then set up the CMyReceiver methods handler1 and handler2 to handle events
(using the intrinsic function __hook) from an event source, which you can create using
event_source.
As before, when the project is built, the compiler parses each C++ source file, producing
an object file. However, when the compiler encounters an attribute, it is parsed and
syntactically verified. The compiler then dynamically calls an attribute provider to insert
code or make other modifications at compile time. The implementation of the provider
differs depending on the type of attribute. For example, ATL-related attributes are
implemented by Atlprov.dll.
The following figure demonstrates the relationship between the compiler and the
attribute provider.
7 Note
Attribute usage does not alter the contents of the source file. The only time the
generated attribute code is visible is during debugging sessions. In addition, for
each source file in the project, you can generate a text file that displays the results
of the attribute substitution. For more information on this procedure, see /Fx
(Merge Injected Code) and Debug injected code.
Like most C++ constructs, attributes have a set of characteristics that defines their
proper usage. This is referred to as the context of the attribute and is addressed in the
attribute context table for each attribute reference topic. For example, the coclass
attribute can only be applied to an existing class or structure, as opposed to the
cpp_quote attribute, which can be inserted anywhere within a C++ source file.
/IDLOUT
/IGNOREIDL
/MIDL
/TLBOUT
Some projects contain multiple independent .idl files. These are used to produce two or
more .tlb files and optionally bind them into the resource block. This scenario is not
currently supported in Visual C++.
In addition, the Visual C++ linker will output all IDL-related attribute information to a
single MIDL file. There will be no way to generate two type libraries from a single
project.
Attribute Contexts
C++ attributes can be described using four basic fields: the target they can be applied
to (Applies To), if they are repeatable or not (Repeatable), the required presence of
other attributes (Required Attributes), and incompatibilities with other attributes
(Invalid Attributes). These fields are listed in an accompanying table in each attribute's
reference topic. Each of these fields is described below.
Applies To
This field describes the different C++ language elements that are legal targets for the
specified attribute. For instance, if an attribute specifies "class" in the Applies To field,
this indicates that the attribute can only be applied to a legal C++ class. If the attribute
is applied to a member function of a class, a syntax error would result.
Repeatable
This field states whether the attribute can be repeatedly applied to the same target. The
majority of attributes are not repeatable.
Required Attributes
This field lists other attributes that need to be present (that is, applied to the same
target) for the specified attribute to function properly. It is uncommon for an attribute
to have any entries for this field.
Invalid Attributes
This field lists other attributes that are incompatible with the specified attribute. It is
uncommon for an attribute to have any entries for this field.
If you know the location of an attribute in a source window, you can use the
shortcut menu to find the injected code in the Disassembly window.
2. In a source code window, place the cursor in front of the attribute whose injected
code you want to view.
If the attribute location is near the current execution point, you can select the
Disassembly window from the Debug menu.
In This Section
Attribute Programming FAQ
Attributes by Group
Attributes by Usage
Attributes Alphabetical Reference
Libraries
Article • 08/03/2021
Visual Studio includes the following libraries when you install one or more of the C++
workloads. For information about installing 3rd-party libraries, see vcpkg.
Standard Libraries
C Runtime Library
C++ Standard Library
SafeInt Library
OpenMP
The Microsoft runtime library provides routines for programming the Microsoft
Windows operating system. These routines automate many common programming
tasks that aren't provided by the C and C++ languages.
Sample programs are included in the individual reference articles for most routines in
the library.
In this section
Universal C runtime routines by category
Provides links to the runtime library by category.
Global constants
Provides links to the global constants defined by the runtime library.
Global state
Describes the scope of global state in the C runtime library.
Generic-text mappings
Provides links to the generic-text mappings defined in Tchar.h.
Debugging
Provides links to using the Visual Studio debugger to correct logic errors in your
application or stored procedures.
C++ Standard Library reference (STL)
Article • 08/17/2022
A C++ program can call on a large number of functions from this conforming
implementation of the C++ Standard Library. These functions perform services such as
input and output and provide efficient implementations of frequently used operations.
For more information about linking with the appropriate Visual C++ runtime .lib file,
see C runtime (CRT) and C++ Standard Library (STL) .lib files.
7 Note
From a historical perspective, "STL" originally referred to the Standard Template Library
written by Alexander Stepanov. Parts of that library were standardized in the C++
Standard Library, along with the ISO C runtime library, parts of the Boost library, and
other functionality. Sometimes "STL" is used to refer to the containers and algorithms
parts of the C++ Standard Library adapted from Stepanov's STL. In this documentation,
Standard Template Library (STL) refers to the C++ Standard Library as a whole.
In this section
C++ Standard Library overview Provides an overview of the Microsoft implementation of
the C++ Standard Library.
Header files reference Provides links to reference topics about the C++ Standard Library
header files, with code examples.
SafeInt Library
Article • 08/03/2021
SafeInt is a portable library that can be used with MSVC, GCC or Clang to help prevent
integer overflows that might result when the application performs mathematical
operations. The latest version of this library is located at
https://github.com/dcleblanc/SafeInt .
In This Section
Section Description
SafeInt Functions Functions that can be used without creating a SafeInt object.
Related Sections
Section Description
C++ Language Reference Reference and conceptual content for the C++ language.
SafeInt Class
Article • 02/17/2022
Extends the integer primitives to help prevent integer overflow and lets you compare
different types of integers.
7 Note
Syntax
C++
Parameters
T
rhs
[in] An input parameter that represents the value on the right side of the operator in
several stand-alone functions.
i
[in] An input parameter that represents the value on the right side of the operator in
several stand-alone functions.
bits
[in] An input parameter that represents the value on the right side of the operator in
several stand-alone functions.
Members
Public Constructors
ノ Expand table
Name Description
Assignment Operators
ノ Expand table
Name Syntax
= template<typename U>
SafeInt<T,E>& operator= (const U& rhs)
= template<typename U>
SafeInt<T,E>& operator= (const SafeInt<U, E>& rhs)
Casting Operators
ノ Expand table
Name Syntax
Comparison Operators
ノ Expand table
Name Syntax
== template<typename U>
!= template<typename U>
Arithmetic Operators
ノ Expand table
Name Syntax
++ SafeInt<T,E>& operator++ ()
-- SafeInt<T,E>& operator-- ()
% template<typename U>
%= template<typename U>
%= template<typename U>
* template<typename U>
*= template<typename U>
Name Syntax
*= template<typename U>
/ template<typename U>
/= template<typename U>
SafeInt<T,E>& operator/= (U i)
/= template<typename U>
+ template<typename U>
+= template<typename U>
+= template<typename U>
- template<typename U>
-= template<typename U>
-= template<typename U>
Logical Operators
ノ Expand table
Name Syntax
^ template<typename U>
^= template<typename U>
^= template<typename U>
| template<typename U>
|= template<typename U>
|= template<typename U>
Remarks
The SafeInt class protects against integer overflow in mathematical operations. For
example, consider adding two 8-bit integers: one has a value of 200 and the second has
a value of 100. The correct mathematical operation would be 200 + 100 = 300. However,
because of the 8-bit integer limit, the upper bit will be lost and the compiler will return
44 (300 - 28) as the result. Any operation that depends on this mathematical equation
will generate unexpected behavior.
The SafeInt class checks whether an arithmetic overflow occurs or whether the code
tries to divide by zero. In both cases, the class calls the error handler to warn the
program of the potential problem.
This class also lets you compare two different types of integers as long as they are
SafeInt objects. Typically, when you do a comparison, you must first convert the
numbers to be the same type. Casting one number to another type often requires
checks to make sure that there is no loss of data.
The Operators table in this topic lists the mathematical and comparison operators
supported by the SafeInt class. Most mathematical operators return a SafeInt object
of type T .
Many binary operators don't support using two different SafeInt types. One example of
this is the & operator. SafeInt<T, E> & int is supported, but SafeInt<T, E> &
SafeInt<U, E> isn't. In the latter example, the compiler does not know what type of
parameter to return. One solution to this problem is to cast the second parameter back
to the base type. By using the same parameters, this can be done with SafeInt<T, E> &
(U)SafeInt<U, E> .
7 Note
For any bitwise operations, the two different parameters should be the same size. If
the sizes differ, the compiler will throw an ASSERT exception. The results of this
operation can't be guaranteed to be accurate. To resolve this issue, cast the smaller
parameter until it's the same size as the larger parameter.
For the shift operators, shifting more bits than exist for the template type will throw an
ASSERT exception. This will have no effect in release mode. Mixing two types of SafeInt
parameters is possible for the shift operators because the return type is the same as the
original type. The number on the right side of the operator only indicates the number of
bits to shift.
When you do a logical comparison with a SafeInt object, the comparison is strictly
arithmetic. For example, consider these expressions:
SafeInt<uint>((uint)~0) > -1
((uint)~0) > -1
The first statement resolves to true , but the second statement resolves to false . The
bitwise negation of 0 is 0xFFFFFFFF. In the second statement, the default comparison
operator compares 0xFFFFFFFF to 0xFFFFFFFF and considers them to be equal. The
comparison operator for the SafeInt class realizes that the second parameter is
negative whereas the first parameter is unsigned. Therefore, although the bit
representation is identical, the SafeInt logical operator realizes that the unsigned
integer is larger than -1.
Be careful when you use the SafeInt class together with the ?: ternary operator.
Consider the following line of code.
C++
C++
If flag is false , the compiler throws an exception instead of assigning the value of -1
to x . Therefore, to avoid this behavior, the correct code to use is the following line.
C++
T and U can be assigned a Boolean type, character type, or integer type. The integer
types can be signed or unsigned and any size from 8 bits to 64 bits.
7 Note
Although the SafeInt class accepts any kind of integer, it performs more efficiently
with unsigned types.
E is the error handling mechanism that SafeInt uses. Two error handling mechanisms
There are two options to customize the error policy. The first option is to set the
parameter E when you create a SafeInt . Use this option when you want to change the
error handling policy for just one SafeInt . The other option is to define
_SAFEINT_DEFAULT_ERROR_POLICY to be your customized error-handling class before
you include the SafeInt library. Use this option when you want to change the default
error handling policy for all instances of the SafeInt class in your code.
7 Note
A customized class that handles errors from the SafeInt library should not return
control to the code that called the error handler. After the error handler is called,
the result of the SafeInt operation can't be trusted.
Inheritance Hierarchy
SafeInt
Requirements
Header: SafeInt.hpp
7 Note
#include "SafeInt.hpp" // set path to your clone of the SafeInt GitHub repo
(https://github.com/dcleblanc/SafeInt)
int main()
{
int divisor = 3;
int dividend = 6;
int result;
Namespace: none
SafeInt::SafeInt
Constructs a SafeInt object.
C++
SafeInt() throw
Parameters
i
[in] The value for the new SafeInt object. This must be a parameter of type T or U,
depending on the constructor.
b
[in] The Boolean value for the new SafeInt object.
u
[in] A SafeInt of type U. The new SafeInt object will have the same value as u, but will
be of type T.
U The type of data stored in the SafeInt . This can be either a Boolean, character, or
integer type. If it's an integer type, it can be signed or unsigned and be between 8 and
64 bits.
Remarks
The input parameter for the constructor, i or u, must be a Boolean, character, or integer
type. If it's another type of parameter, the SafeInt class calls static_assert to indicate an
invalid input parameter.
The constructors that use the template type U automatically convert the input
parameter to the type specified by T . The SafeInt class converts the data without any
loss of data. It reports to the error handler E if it can't convert the data to type T
without data loss.
If you create a SafeInt from a Boolean parameter, you need to initialize the value
immediately. You can't construct a SafeInt using the code SafeInt<bool> sb; . This will
generate a compile error.
SafeInt Functions
Article • 08/03/2021
The SafeInt library provides several functions that you can use without creating an
instance of the SafeInt class. If you want to protect a single mathematical operation
from integer overflow, you can use these functions. If you want to protect multiple
mathematical operations, you should create SafeInt objects. It's more efficient to create
SafeInt objects than to use these functions multiple times.
Each of these functions has two template types: T and U . Each of these types can be a
Boolean, character, or integral type. Integral types can be signed or unsigned and any
size from 8 bits to 64 bits.
7 Note
In This Section
Function Description
SafeAdd
Adds two numbers in a way that protects against overflow.
C++
Parameters
t
[in] The first number to add. This must be of type T.
u
[in] The second number to add. This must be of type U.
result
[out] The parameter where SafeAdd stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeCast
Casts one type of number to another type.
C++
template<typename T, typename U>
inline bool SafeCast (
const T From,
U& To
);
Parameters
From
[in] The source number to convert. This must be of type T .
To
[out] A reference to the new number type. This must be of type U .
Return Value
true if no error occurs; false if an error occurs.
SafeDivide
Divides two numbers in a way that protects against dividing by zero.
C++
Parameters
t
[in] The dividend. This must be of type T.
u
[in] The divisor. This must be of type U.
result
[out] The parameter where SafeDivide stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeEquals
Compares two numbers to determine whether they're equal.
C++
Parameters
t
[in] The first number to compare. This must be of type T.
u
[in] The second number to compare. This must be of type U.
Return Value
true if t and u are equal; otherwise false .
Remarks
The method enhances == because SafeEquals enables you to compare two different
types of numbers.
SafeGreaterThan
Compares two numbers.
C++
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is greater than u; otherwise false .
Remarks
SafeGreaterThan extends the regular comparison operator by enabling you to compare
two different types of numbers.
SafeGreaterThanEquals
Compares two numbers.
C++
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is greater than or equal to u; otherwise false .
Remarks
SafeGreaterThanEquals enhances the standard comparison operator because it enables
SafeLessThan
Determines whether one number is less than another.
C++
Parameters
t
[in] The first number. This must be of type T .
u
[in] The second number. This must be of type U .
Return Value
true if t is less than u; otherwise false .
Remarks
This method enhances the standard comparison operator because SafeLessThan
enables you to compare two different types of number.
SafeLessThanEquals
Compares two numbers.
C++
template <typename T, typename U>
inline bool SafeLessThanEquals (
const T t,
const U u
) throw ();
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t is less than or equal to u; otherwise false .
Remarks
SafeLessThanEquals extends the regular comparison operator by enabling you to
SafeModulus
Performs the modulus operation on two numbers.
C++
Parameters
t
[in] The divisor. This must be of type T .
u
[in] The dividend. This must be of type U .
result
[out] The parameter where SafeModulus stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeMultiply
Multiplies two numbers together in a way that protects against overflow.
C++
Parameters
t
[in] The first number to multiply. This must be of type T .
u
[in] The second number to multiply. This must be of type U .
result
[out] The parameter where SafeMultiply stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeNotEquals
Determines if two numbers aren't equal.
C++
Parameters
t
[in] The first number to compare. This must be of type T .
u
[in] The second number to compare. This must be of type U .
Return Value
true if t and u aren't equal; otherwise false .
Remarks
The method enhances != because SafeNotEquals enables you to compare two different
types of numbers.
SafeSubtract
Subtracts two numbers in a way that protects against overflow.
C++
Parameters
t
[in] The first number in the subtraction. This must be of type T .
u
[in] The number to subtract from t. This must be of type U .
result
[out] The parameter where SafeSubtract stores the result.
Return Value
true if no error occurs; false if an error occurs.
SafeIntException Class
Article • 08/03/2021
7 Note
Syntax
C++
class SafeIntException;
Members
Public Constructors
Name Description
Remarks
The SafeInt class is the only class that uses the SafeIntException class.
Inheritance Hierarchy
SafeIntException
Requirements
Header: safeint.h
Namespace: msl::utilities
SafeIntException::SafeIntException
Creates a SafeIntException object.
C++
SafeIntException();
SafeIntException(
SafeIntError code
);
Parameters
code
[in] An enumerated data value that describes the error that occurred.
Remarks
The possible values for code are defined in the file Safeint.h. For convenience, the
possible values are also listed here.
SafeIntNoError
SafeIntArithmeticOverflow
SafeIntDivideByZero
MFC and ATL
Article • 09/21/2021
The Microsoft Foundation Classes (MFC) provide a C++ object-oriented wrapper over
Win32 for rapid development of native desktop applications. The Active Template
Library (ATL) is a wrapper library that simplifies COM development and is used
extensively for creating ActiveX controls.
You can create MFC or ATL programs with Visual Studio Community Edition or higher.
The Express editions do not support MFC or ATL.
In Visual Studio 2015, Visual C++ is an optional component, and MFC and ATL
components are optional sub-components under Visual C++. If you do not select these
components when you first install Visual Studio, you will be prompted to install them
the first time you attempt to create or open an MFC or ATL project.
In Visual Studio 2017 and later, MFC and ATL are optional sub-components under the
Desktop development with C++ workload in the Visual Studio Installer program. You
can install ATL support without MFC, or combined MFC and ATL support (MFC depends
on ATL). For more information about workloads and components, see Install Visual
Studio.
Related Articles
Title Description
MFC Desktop Microsoft Foundation Classes provide a thin object-oriented wrapper over
Applications Win32 to enable rapid development of GUI applications in C++.
ATL COM ATL provides class templates and other use constructs to simplify creation of
Desktop COM objects in C++.
Components
ATL/MFC Shared References for CStringT Class and other classes that are shared by MFC and
Classes ATL.
Working with The resource editor lets you edit UI resources such as strings, images, and
Resource Files dialog boxes.
Visual C++ provides the following technologies to help you create multi-threaded and
parallel programs that take advantage of multiple cores and use the GPU for general
purpose programming.
Related Articles
Title Description
Concurrency Runtime Classes that simplify the writing of programs that use data
parallelism or task parallelism.
C++ AMP (C++ Accelerated Classes that enable the use of modern graphics processors for
Massive Parallelism) general purpose programming.
Multithreading Support for Older technologies that may be useful in older applications. For
Older Code (Visual C++) new apps, use the Concurrency Runtime or C++ AMP.
C++ in Visual Studio This section of the documentation contains information about
most of the features of Visual C++.
Data Access in Visual C++
Article • 08/03/2021
Virtually all database products, SQL and NoSQL, provide an interface for native C++
applications. The industry standard interface is ODBC which is supported by all major
SQL database products and many NoSQL products. For non-Microsoft products, consult
the vendor for more information. Third-party libraries with various license terms are also
available.
Since 2011 Microsoft has aligned on ODBC as the standard for native applications to
connecting to Microsoft SQL Server databases, both on-premises and in the cloud. For
more information, see Data Access Programming (MFC-ATL). C++/CLI libraries can use
either the native ODBC drivers or ADO.NET. For more information, see Data Access
Using ADO.NET (C++/CLI) and Accessing data in Visual Studio.
In This Section
Data Access Programming (MFC/ATL)
Describes legacy data access programming with Visual C++, where the preferred way is
to use one of the class libraries such as the Active Template Class Library (ATL) or
Microsoft Foundation Class (MFC) Library, which simplify working with the database
APIs.
OLE DB Programming
A mostly legacy interface which is still required in some scenarios, specifically when you
are programming against linked servers.
Related Topics
Connect to SQL Database using C and C++
Connect to Azure SQL Database from C or C++ applications.
See also
C++ in Visual Studio