Quantcast
Channel: C++ Team Blog
Viewing all 1541 articles
Browse latest View live

Bring your existing C++ Linux projects to Visual Studio

$
0
0

Visual Studio supports targeting Linux out of the box – you can edit, remote build and remote debug to a Linux machine (whether that’s a remote machine, a VM running locally or in the cloud, or WSL in Windows 10).

This article covers the high-level steps to bring your existing Linux projects to Visual Studio. You can read about other C++ project types in the guide for Bringing your C++ code to Visual Studio.

Step 1. Install: Just make sure that you select the C++ Linux workload as part of the VS installation.

bringcode-linux-install

Step 2. Generate VS project: The next step is to create a VS Linux makefile project

$ ./genvcxproj.sh ~/repos/preciouscode/ preciouscode.vcxproj Z:

Step 3. Configure VS project properties: You will need to specify in Project Properties (right click on project in Solution Explorer) > Remote Build > Build Command Line the exact command you use on your Linux machine to build the sources. In addition, you will want to specify the additional include path that VS IntelliSense can use to properly aid when editing the code.

bringcode-linux-propertypages

After these steps, you will be able to edit and browse your C++ code, build and debug remotely.

bringcode-linux-debug

What’s next

Follow the links to learn more about Visual C++ for Linux development and Targeting the Windows Subsystem for Linux from Visual Studio.

If you’re new to Visual Studio, learn more by reading the Getting Started with Visual Studio for C and C++ Developer topic (Coming soon!) and the rest of the posts in this Getting Started series aimed at C++ users that are new to Visual Studio. Download Visual Studio 2017 today, try it out and share your feedback.


Bring your existing Android Eclipse projects to Visual Studio

$
0
0

You can use Visual Studio to develop your C++ projects targeting Android. To learn more about this support read the Visual C++ for Cross-Platform Mobile development section on MSDN.

If you’re currently using Eclipse and considering moving to Visual Studio, you can do that via our Eclipse Android Project Import Wizard. You can read about other C++ project types in the guide for Bringing your C++ code to Visual Studio.

Step 1. Install Android Support: Make sure that during VS installation, you select the “Mobile development with C++” workload. By default, it already includes all the prerequisites needed to build C++ Android projects.

bringcode-md-install

Step 2. Install the Eclipse Import Wizard extension: From the Marketplace, install the Java Language Service for Android and Eclipse Android Project Import extension.

Step 3. Run the import wizard: Launch the wizard from File > New > Android Projects from Eclipse and follow the instructions

bringcode-md-eclipse-wizard

When the wizard completes, you will have projects for both the C++ parts and the Java parts of your Android Eclipse project. You can develop your Android project by editing, building and debugging both C++ and Java code.

bringcode-md-slnexplorerbringcode-md-debug

What’s next

If you’re new to Visual Studio, learn more by reading the Getting Started with Visual Studio for C and C++ Developer topic (Coming soon!) and the rest of the posts in this Getting Started series aimed at C++ users that are new to Visual Studio. Download Visual Studio 2017 today, try it out and share your feedback.

Migrate your existing iOS XCode projects to Visual Studio

$
0
0

If you’re targeting iOS and writing a lot of C++ code, you should consider importing your XCode projects inside Visual Studio. Visual Studio not only provides an easy way to import these projects, but also allows opening these projects back in XCode if you need to make non-C++ related edits (e.g. storyboarding, UI design).

This article covers the high-level steps needed to import your existing iOS XCode projects into Visual Studio. You can read about other C++ project types in the guide for Bringing your C++ code to Visual Studio.

Step 1. Install iOS support: Make sure that during VS installation, you select the “Mobile development with C++” workload. In the customization pane, make sure you select the “C++ iOS development tools” option as well.

bringcode-ios-install

bringcode-ios-install-options

Step 2. Install the remote Mac tools and connect from VS: Install vcremote on the Mac machine following the instructions in “Install and Configure Tools to Build iOS projects”. Then, in VS, from Tools > Options > Cross Platform > C++ > iOS, pair VS with your Mac machine

bringcode-ios-options

Step 3. Launch the XCode import wizard. Go to File > New > Import > Import from XCode and follow the steps of the wizard. To learn more about the wizard, read “Import a XCode project” in MSDN

bringcode-ios-import

Each XCode target will create a new Visual Studio project and your iOS source code will be available for further editing, building and debugging.

bringcode-ios-debug

Step 4 (optional). Open Visual Studio project in XCode: When you need to make non-C++ changes to your iOS projects (e.g. storyboard editing), Visual Studio can automatically open your projects inside XCode running on your Mac. Once you’re done making changes, you can ask VS to copy these changes back to the Windows machine. Follow this link to learn more about syncing changes between XCode and Visual Studio.

bringcode-ios-xcode

What’s next

To learn more about the iOS support in Visual Studio read “Developing cross-platform iOS applications using Visual Studio”.

If you’re new to Visual Studio, learn more by reading the Getting Started with Visual Studio for C and C++ Developer topic (Coming soon!) and the rest of the posts in this Getting Started series aimed at C++ users that are new to Visual Studio. Download Visual Studio 2017 today, try it out and share your feedback.

Migrate your existing Windows C++ projects to MSBuild

$
0
0

If your project targets one of the Windows platforms only (Desktop or UWP), you should consider using MSBuild as your C++ build system. If you consider expanding beyond these platforms though, consider using CMake to specify your build. To learn more, read about the CMake support in Visual Studio.

Using MSBuild has the benefit that from a single codebase you can easily target all the Windows platforms that VS supports today, and you can leverage the C++ Project System that provides file and project management functionality. This makes it easy to manage your project as it grows (easily adding project references between projects, configuring PCHs, configuring compiler and linker switches across multiple projects, etc.).

This article covers the high-level steps needed to migrate your existing C++ code targeting Windows to use MSBuild. You can read about other C++ project types in the guide for Bringing your C++ code to Visual Studio.

Step 1. Run the Project from Existing Code wizard: Launch “File > New > Project from existing code…” and follow the wizard steps to create a new VS project for your sources. On the “Specify Project Settings” step, make sure you select “Use Visual Studio” before configuring any other option that might apply (e.g. using MFC, ATL or CLR).

bringcode-win-wizard

Step 2. Translate compile options to VS: For this step, it’s recommended to turn up the verbosity of MSBuild (from Tools > Options > Projects and Solutions > Build and Run, change “MSBuild project build output verbosity” to “Detailed”). This step will list the compiler command lines that MSBuild uses to run the build. You can compare this against a log of the previous build system you were using.

Differences can be reconciled in the Project Properties dialog (right-click on the project in Solution Explorer and select “Properties”) > Configuration Properties > C/C++ > All Options. In the search box, you can search for a specific switch to find the property that maps to that switch and operate changes to make sure that MSBuild ends up calling the compiler with the same command line that your previous build system was.

bringcode-win-proppages

Step 3. Use Shared code projects: If you want to expand your project to target more platforms in addition to Windows, follow the instructions in the “Cross-platform code sharing with Visual C++” article to move your C++ code into a shared code project and share it among C++ projects targeting Windows, UWP, Android or iOS.

bringcode-win-shared

bringcode-win-slnexplorer

Step 4. Consume 3rd party C++ libraries. If your project is depending on any open-source C++ libraries today, chances are that you will find them in vcpkg’s catalog. Vcpkg can easily integrate with MSBuild projects and can simplify both the build process for these 3rd party open-source libraries as well as the consumption in your own projects. To learn more about vcpkg, check out the Getting started with vcpkg introductory post.

What’s next

If you’re new to Visual Studio, learn more by reading the Getting Started with Visual Studio for C and C++ Developer topic (Coming soon!) and the rest of the posts in this Getting Started series aimed at C++ users that are new to Visual Studio. Download Visual Studio 2017 today, try it out and share your feedback.

Bring your C++ code to Visual Studio

$
0
0

C++ has been around for a long time and throughout its history many tools have been built to make life easier for C++ developers. This has led to a diverse C++ ecosystem in terms of the editing tools, build systems, coding conventions, and C++ libraries that we use in our day-to-day work. As a C++ developer, you are probably accustomed to using a variety of tools from different vendors for different purposes. Rest assured that you will not trade-in your flexibility in how you develop your C++ projects once you start using Visual Studio. Visual Studio provides industry-leading development tools for C++ for any platform you’re targeting.

Depending on a few characteristics of your C++ project, this document will guide you through the recommended steps to get started with Visual Studio. Read on each chapter to see if it fits the description of your project. This post is part of a Getting Started series aimed at C++ users that are new to Visual Studio.

Cross-platform C++ applications and libraries

Building with CMake

If your project targets multiple platforms, you are likely to use CMake to specify your build. The steps needed to move to Visual Studio are very simple in this case – just open the folder containing your CMakeLists.txt files and let Visual Studio do the rest. To learn more about using CMake in Visual Studio, read the CMake support in Visual Studio page.

Targeting Qt Framework or building with QMake

Qt framework is a cross-platform C++ framework; it is ideal for building desktop, mobile and even embedded solutions. While you can use CMake to target Qt (in which case you should review the above topic), Qt also offers its own Qt-optimized build system called qmake that supports non-Qt C++ projects as well. If you are using qmake, learn how to import your .pro projects into Visual Studio.

Building with a cross-platform C++ build system (make, ninja, gyp, scons, gradle, etc.)

There are many build systems that support C++ today for cross-platform scenarios. It is outside the scope of this document to recommend one over another. But regardless of which build system your project uses today, you can open it inside Visual Studio and with minimal configuration you can become productive. With any of these build systems, you can enable all or any of the following Visual Studio capabilities:

  • C++ editing (e.g. IntelliSense, code navigation)
  • Building
  • C++ debugging (e.g. Windows process debugging, attaching, remote debug, etc.)

To learn how to move to Visual Studio, read more about Open Folder support in Visual Studio 2017.

Linux C++ applications (including targeting server, cloud, IoT)

Are you developing a server-side component or a containerized binary running on Linux or maybe a critical component for an IoT device? Visual Studio provides support for targeting Linux out-of-the-box. You can edit, build and debug your C++ projects either by using a remote Linux machine or using the built-in Windows 10 Linux subsystem support. For a step-by-step guide to porting your projects to Visual Studio read Bring your existing C++ Linux projects to Visual Studio.

Android C++/Java applications

Using Eclipse

You can use Visual Studio to develop both your C++-only projects as well as C++/Java JNI-based projects targeting Android. If you’re currently using Eclipse, you can move to Visual Studio via our Eclipse Android Project Import Wizard. Follow the link to learn more about migrating your Eclipse Android projects to Visual Studio.

Using Gradle

Whether you already have a gradle-based build for your Android project, or you are just getting started targeting Android, Visual C++ provides the support you need to build Gradle projects. Visual C++ also offers a great editing and debugging experience for both your C++ and Java source code. To learn more, read about building your Android applications in Visual Studio using Gradle.

iOS Objective-C/C++ applications

If you’re targeting iOS and writing a lot of C++ code, you should consider importing your XCode projects into Visual Studio. Visual Studio not only provides an easy way to import these projects, but also allows opening these projects back in XCode if you need to make non-C++ related edits (e.g. storyboarding, UI design). Follow this link to learn more about migrating your XCode iOS projects to Visual Studio.

Windows C++ application

If your project targets Windows, you should consider using MSBuild as your C++ build system. With MSBuild, you can target from a single codebase all the platforms that Visual Studio supports today. You also get access to the C++ Project System that provides file and project management functionality that makes it easy to manage your project as it grows. You can easily addi references between projects, configuring PCH file, and configur compiler and linker switches across multiple projects). Learn more about migrating your C++ project to MSBuild.

What’s next

If you’re new to Visual Studio, learn more by reading the Getting Started with Visual Studio for C and C++ Developer topic (Coming soon!) and the rest of the posts in this Getting Started series aimed at C++ users that are new to Visual Studio. Download Visual Studio 2017 today, try it out and share your feedback.

If your C++ development scenarios are not covered today by Visual Studio, don’t hesitate to reach out to us at visualcpp@microsoft.com. We would love to learn more about it

Windows desktop development with C++ in Visual Studio

$
0
0

The Windows desktop platform has long been the most popular platform among C++ application developers.  With C++ and Visual Studio, you use Windows SDKs to target many versions of Windows ranging from Windows XP to Windows 10, which is well over a billion devices.  Popular desktop applications like Microsoft Office, Adobe Creative Suite, and Google Chrome all are built using the same Win32 APIs that serve as the foundation for Windows desktop development.  Developing for Windows desktop allows you to reach the highest number of users on any non-mobile development platform.

In this post we will dive into the “Desktop development with C++” workload inside Visual Studio and go over the workflow used to develop a desktop app.  For information on developing Universal Windows Platform apps, check out this post.

Acquiring the tools

After installing Visual Studio, open the Visual Studio Installer from the Start menu and navigate to the Workloads Page. We need to install the “Desktop development with C++” workload, which provides the tools needed for developing Windows desktop applications that can run on Windows.  The Win32 API model used in these types of applications is the development model used in Windows versions prior to the introduction of the modern Windows API that began with Windows 8.  This modern API later evolved into the UWP platform for Windows 10, but traditional desktop development using Windows APIs is still fully supported on all versions of Windows.

When you install the C++ Windows desktop workload, you have many options to customize the installation by selecting your desired tools, Windows SDKs, and other additional features like recent ISO C++ standards candidates such modules support for the STL.  The core C++ compiler and libraries for building desktop applications that target x86 and x64 systems are included in the VC++ 2017 v141 toolset (x86, x64).  Notable optional tools include support for MFC and C++/CLI development.  In the following examples, we will show how to create an MFC app, so this optional component was installed.

desktopwl

Opening code and building

After installing the C++ desktop workload, you can begin coding in existing projects or you can create new ones. Out of the box, Visual Studio can open any folder of code and be configured to build using CMake, a cross-platform build system. The Visual Studio CMake integration even allows you to use another compiler by opening the directory containing your CMakeLists.txt files and let VS do the rest.

Of course ,there is also full support for Microsoft’s own build system called MSBuild, which uses the .vcxproj file format.  MSBuild is a robust and fully featured build system that allows building projects in Visual Studio that target Windows. Building an MSBuild-based project just requires a .vcxproj file and can be built in the IDE or by using the command prompt.

In Visual Studio 2017, you can also simply open a folder of code files and immediately begin working in it. In the background, Visual Studio will index your files and providing Intellisense support along with refactoring and all the other navigation aids that you expect. You can create custom .json scripts to specify build configurations.

Creating new projects

If you are creating a new project from scratch, then you can start with one of a variety of project templates.: Each template provides customizable build configurations and boilerplate code that compiles and runs out of the box:

Project Type (folder) Description
Win32 The Win32 API (also known as the Windows API) is a C-based framework for creating GUI-based Windows desktop applications that have a message loop and react to Windows messages and commands. A Win32 console application has no GUI by default and runs in a console window from the command line.
ATL The Active Template Library is a set of template-based C++ classes that let you create small, fast Component Object Model (COM) objects. COM
MFC Microsoft Foundation Classes is an object oriented wrapper over the Win32 API that provides designers and extensive code-generation support for creating a native UI.
CLR C++/CLI (Common Language Interface) enables  efficient communication between native C++ code and .NET code written in languages such as C# or Visual Basic.

Project templates are included for each of these types of desktop applications depending on the features you select for the workload.

templates

Project Wizard

Once you have selected a template, you have the option to customize the project you have selected to create.  Each of these project types has a wizard to help you create and customize your new project.  The illustrations below show the wizard for an MFC application.

wizard

The wizard creates and opens a new project for you and your project files will show up in Solution Explorer.

solnexp

At this point, even before you write a single line of code, you can build and run the application by pressing F5.

mfcapp

Editing code and navigating

Visual Studio provides many features that help you to code correctly and more efficiently. Whether it be the powerful predictive capabilities provided by IntelliSense or the fluid navigation found in Navigate To there is a feature to make almost any action faster inside Visual Studio.  Let Visual Studio do the work for you with autocompletion simply by pressing Tab on the item you want to add from the member list.

intellisense

You can also hover over any variable, function, or other code symbol and get information about that symbol using the quick info feature.

infotip

There are also many great code navigation features to make dealing with large code bases much more productive, including Go To Definition, Go To Line/Symbols/Members/Types, Find All References, View Call Hierarchy, Object Browser, and more.  Peek Definition allows you to view the code that defines the selected variable without even having to open another file which minimizes context switching.

codepeak

We also have support for some of the more common refactoring techniques like rename and extract function that allow you to keep your code looking nice and consistent.

Debugging and Diagnostics

Debugging applications is what Visual Studio is famous for!  With a world-class debugging experience that provides a plethora of tools for any type of app, no tool is better suited to debugging applications that target the Windows desktop platform.

datatip

Powerful features like advanced breakpoints, custom data visualization, and debug-time profiling enable you to have full control of your app’s execution and pinpoint even the hardest to find bugs.  View data values from your code with debugger data tips.  Take memory snapshots and diff them to reveal potential memory leaks, and even invoke PageHeap on your app from inside Visual Studio to help solve the notoriously hard problem of memory corruption.  Track live CPU and memory usage while your application runs and monitor performance in real-time.hub

Testing your code

Unit testing is a very popular way of improving code quality, and test-driven-development is fully supported inside Visual Studio.   Create new tests and manage them inside the Test Explorer for easy tracking and execution of tests.  Writing unit tests is easy and can help find problems as they arise instead of later on when things are harder to isolate.  Visual Studio allows both native and managed test project templates for testing native code which can be found in the Visual C++/Test section of the new project templates.  Note that the native test template comes with the C++ desktop workload and the managed test comes with the .NET desktop workload.

test

Working with others

Besides all of the individual developer activities that Visual Studio makes more productive, collaboration is also something that is directly integrated into the IDE.  Visual Studio Team Services is a suite of features that optimize the team collaboration process for software development organizations.  Create work items, track progress, and manage your bug and open issue database all from inside Visual Studio.  Git is fully supported and works seamlessly with the Team Explorer, allowing for easy management of branches, commits, and pull requests.

teamexp

Simply sign up for a Visual Studio Team Services account for free, then you can track the source code of your desktop applications into Visual Studio Team Services.  Visual Studio Team Services also simplifies continuous integrations for your desktop applications. Create and manage build processes that automatically compile and test your apps in the cloud.

Windows Store packaging for desktop apps

When you are ready to deploy your desktop application, you would typically build an executable (.exe) and possibly some libraries so that your application can run on a Windows device.  This allows you to easily distribute your application however you like, for example via a download from your website or even through a third-party sales platform such as Steam.

A new option for Windows desktop apps is to be available in the Windows Store with all the advantages that entails. The Desktop Bridge project allows you to package and distribute your Win32 application through the Windows Store alongside Universal Windows Platform apps. When targeting Windows 10, this can provide advantages including streamlined deployment, greater reach, simpler monetization, simplified setup authoring, and differential updates.

Try out Visual Studio 2017 for desktop development with C++!

Download Visual Studio 2017, try it out and share your feedback.  For problems, let us know via the Report a Problem option in the upper right corner of the VS title bar.  Track your feedback on the developer community portal. For suggestions, let us know through UserVoice.

Universal Windows Platform Development with C++

$
0
0

Universal Windows Platform (UWP) applications utilize a new Windows API and app model that creates a single output binary that can feasibly run on any Windows 10 device, ranging from desktops to HoloLens.  Because a app can run on a wide variety of devices with different form factors and types of input, you want it to be tailored to each device and be able to unlock the unique capabilities of each device.  In addition to the guaranteed core API layer, you can write code to access device specific APIs so that your app lights up features specific to one type of device while presenting a different experience on other devices.  Adaptive UI controls and new layout panels help you to tailor your UI across a broad range of device screen resolutions and sizes.

uwp

In this blog post we will dive into the specifics of how to create a C++ UWP application and how Visual Studio makes this a great experience:

C++ and the Universal Windows Platform

There are a few ways to write a C++ UWP app:

  • C++/CX is Microsoft’s language extension for C++ that allows it to target the Windows Runtime that was released with Windows 8 and continues to evolve with Windows 10.
  • The Windows Runtime Library is a template library that provides a low-level way to author and use Windows Runtime components.
  • C++/WinRT is a recently implemented standard C++ language projection for the Windows Runtime implemented solely in header files. It allows you to both author and consume Windows Runtime APIs using any standards-compliant C++ compiler. C++/WinRT is designed to provide C++ developers with first-class access to the modern Windows API.A recent alternative called CppWinRT is a language conformant wrapper for the WinRT APIs that allows you to use modern and compliant C++ code to targets Windows 10.

Acquiring the tools

uwpwl

The Visual Studio workload that provides the tools for creating UWP apps and has an optional installation component that is required for C++ UWP development called “C++ Universal Windows Platform tools”:

uwpwloptions

Opening code and building

Universal Windows Platform apps use Microsoft’s own build system called MSBuild, which uses the same .vcxproj file format that is used in the new project templates for desktop development.

MSBuild is a robust and fully featured build system that allows building projects in Visual Studio that target Windows. Building an MSBuild-based project just requires a .vcxproj file and can be built in the IDE or using the command prompt.

Creating new projects

The UWP development tools provide a number of different templates for you to choose from, including templates for DirectX 11 and Direct X12.  A Windows Runtime Component is very similar to a library, but only uses the WinRT APIs available to modern Windows applications.  These components can be shared across all supported Windows Runtime languages that support UWP development, which include C#, Visual Basic, JavaScript, and C++.

uwptemplate

In order to deploy local UWP applications in Windows 10, you must first enable “Developer mode” which can be done after creating a UWP project. This will find and install the latest packages for Store app deployment and allow you to deploy the UWP apps you develop in Visual Studio.

uwpmode

After activating developer mode in Windows 10, you can now build and deploy Universal Windows Platform applications, like this spinning cube that is provided in the DirectX templates.

uwpcube

Editing code and navigating

Visual Studio provides many features that help you to code correctly and more efficiently. Whether it be the powerful predictive capabilities provided by IntelliSense or the fluid navigation found in Navigate To.  Let Visual Studio do the work for you with autocompletion simply by pressing Tab on the item you want to add from the member list.

intellisense

You can hover also over any variable, function, or other code symbol and get information about that symbol using the quick info feature.

infotip

There are also many great code navigation features to make dealing with large code based much more productive, including Go To Definition, Go To Line/Symbols/Members/Types, Find All References, View Call Hierarchy, Object Browser, and more.  Peek Definition allows you to view the code that defines the selected variable without even having to open another file which minimizes context switching.

codepeak

We also have support for some of the more common refactoring techniques like rename and extract function that allow you to keep your code looking nice and consistent.

Debugging and diagnostics

Debugging applications is what Visual Studio is famous for!  With a world-class debugging experience that provides a plethora of tools for any type of app, no tool is better suiting to debugging applications that target the Windows desktop platform.

datatip

Powerful features like the advanced breakpoints, custom data visualization, and debug-time profiling enable you to have full control of your app’s execution and pinpoint even the hardest to find bugs.  View data values from your code with debugger data tips.  Take memory snapshots and diff them to reveal potential memory leaks, and even invoke PageHeap on your app from inside Visual Studio to help solve the notoriously hard problem of memory corruption.  Track live CPU and memory usage while your application runs and monitor performance in real-time.

hub

Testing your code

Unit testing is a very popular way of improving code quality, and test-driven-development is fully supported inside Visual Studio.  Create new tests and manage them inside the Test Explorer for easy management and execution of tests.  Writing unit tests is easy and can help find problems as they arise instead of later on when things are harder to isolate.  Visual Studio allows both native and managed test project templates for testing native code which can be found in the Visual C++àTest section of the new project templates.

test

Working with others

Besides all of the individual developer activities that Visual Studio makes more productive, collaboration is also something that is directly integrated into the IDE.  Visual Studio Team Services is a suite of features that optimize the team collaboration process for software development organizations.  Create work items, track progress, and manage your bug and open issue database all from inside Visual Studio.  Git is fully supported and works seamlessly with the Team Explorer, allowing for easy management of branches, commits, and pull requests.

teamexp

Packaging your app for the Windows Store

There are few steps required to package your app so that you can distribute it on the Windows Store.  First, make sure you are a registered Windows app developer.  Once you are registered and have a tested and optimized app you are interested in publishing, you can select your packaging options in the app manifest file (package.appxmanifest).  This detailed packaging guide will walk you through the rest of steps needed to get your app ready for distribution and submit it to the Windows Store.

packaging

Try out Visual Studio 2017 for UWP development with C++!

Download Visual Studio 2017, try it out and share your feedback.  For problems, let us know via the Report a Problem option in the upper right corner of the VS title bar.  Track your feedback on the developer community portal. For suggestions, let us know through UserVoice.

CMake support in Visual Studio – what’s new in 2017 15.2 update

$
0
0

Today’s preview release of Visual Studio 2017 15.2 update comes with several improvements and new features in CMake Tools for Visual Studiorecently updated to cover 15.2.  We have upgraded the included version of CMake to 3.7.2 and enhanced the discoverability of features in the CMake menu.  This update also includes bugfixes for community reported issues.

Please download the preview and try out the latest CMake features.  If you are just getting started with CMake, follow the link to learn more about CMake support in Visual Studio.  We are looking forward to your feedback.

CMake Tools Upgraded to CMake 3.7.2

We want to make Visual Studio the best way to work with CMake projects on Windows.  To enhance compatibility with your projects, we have updated the internal version of CMake that the Visual Studio CMake tools use from version 3.6 to version 3.7.2.

CMake 3.7.2 brings many new features and improvements, which you can read about in CMake’s 3.7 release notes.  On the IDE side, the update to CMake 3.7.2 gives Visual Studio more insight into your projects’ structure and allows Visual Studio to provide more accurate IntelliSense and builds.

A More Intuitive CMake Menu

The most visible change that many of you will notice in the update is the revamped CMake menu:

Visual Studio 2017 15.2 Update CMake Menu

The revamped menu brings all the common operations to the forefront.  At the top of the menu Build, Rebuild, Clean, and (if applicable) Test All apply globally to every CMake project detected in an open folder.  The menu items below those allow finer control, such as building individual targets and managing the CMake cache.  This menu should now be a one stop shop for all things CMake instead of having operations and entry points scattered around the IDE.

Bugfixes and Improvements

The 15.2 update includes many improvements and addresses several bugs, most of which were reported by the community.  The following issues have been fixed in the latest release:

  • Visual Studio fails to launch CMake targets because the output location cannot be found for some CMakeLists.
    Developer Community: 24375 24359
  • CMake tools freeze or malfunction when the build output is a child of the opened folder.
    Developer Community: 12830 25412
  • Running tests triggers installation stage.
    Developer Community: 19007
  • Tests attempt to run even when build fails.
    Developer Community: 17949
  • No way to pass arguments to tests via CMakeSettings.json.
    Developer Community: 17968
  • CMake processing appears to be stalled and cannot be canceled for large or unsupported CMakeLists.
    Developer Community: 9879 13799 15384 24404 31401
  • Visual Studio does not automatically restart cache generation after a failure upon re-opening a folder.
    Developer Community: 13185
  • Visual Studio does not support CMake workspaces with long paths.
    Developer Community: 9222
  • CMake cache generation fails if standard tools are not in toolbar.
    Developer Community: 37195
  • CMake Tools for Visual Studio do not support “Rebuild All”
    Developer Community: 22318
  • CMake output pane shows incomplete status during cache generation and IntelliSense configuration.

Send Us Feedback

To try out the latest and greatest CMake features and give us some early feedback, please download and install the latest Visual Studio 2017 Preview.  As always, we welcome your feedback.  Feel free to send any comments through e-mail at visualcpp@microsoft.com, through Twitter @visualc, or Facebook at Microsoft Visual Cpp.

If you encounter other problems with Visual Studio 2017 please let us know via Report a Problem, which is available in both the installer and the IDE itself.  For suggestions, let us know through UserVoice. We look forward to your feedback!


Android and iOS development with C++ in Visual Studio

$
0
0

When it comes to building mobile applications, many developers write most or a part of the apps in C++. Why? Those who are building computationally intensive apps such as games and physics simulations choose C++ for its unparalleled performance, and the others choose C++ for its cross-platform nature and the ability to leverage existing C/C++ libraries in their mobile applications. Whether you’re targeting Universal Windows Platform (UWP), Android, or iOS, Visual Studio enables building cross-platform C++ mobile applications with full editing and debugging capabilities all in one single IDE.

In this blog post, we will focus on how to build Android and iOS apps with C++ in Visual Studio. First we will talk a look at how to acquire the tools for Android and iOS development, then we will create a few C++ mobile apps using the built-in templates. Next we will use the Visual Studio IDE to write C++ and Java code, then we will use the world-class Visual Studio debugger to catch issues in C++ and Java code. Finally, we will talk about how the C++ mobile solution can be used in conjunction with Xamarin.

Install Visual Studio for Android and iOS development

First, download Visual Studio 2017 and launch the Visual Studio installer.

To build Android or iOS applications, choose the “Mobile development with C++” workload under the “Mobile & Gaming” category.

1-vs-install

Android development: By default, this workload includes the core Visual Studio editor, the C++ debugger, GCC and Clang compilers, Android SDKs and NDKs, Android build tools, Java SDK, and C++ Android development tools. You could choose to install the Google Android Emulator in the Optional Component list if you don’t have an Android device for testing. This should give you everything you need to start building Android applications.

iOS development: if you’re also targeting iOS, check “C++ iOS development tools” in the Optional Component list and you would be good to go.

Create a new Android application using project templates

If you plan to start with targeting Android first and worry about other platforms later, the VS built-in Android project templates including Native-Activity Application, Static Library, Dynamic Shared Library, could be a great starting point. If you’d rather start with a cross-platform solution to target multiple mobile platforms, jump to the next section Build an OpenGLES Application on Android and iOS where we’ll talk about building an app that targets both platforms with shared C++ code.

You can find the Android templates under Visual C++ -> Cross Platform -> Android node.

2-templates

Here we’re going to create a new Native Activity Application (Android), which is popular for creating games and graphical-intensive apps. Once the project is created, in the Solution Platforms dropdown, choose the right architecture that matches the Android emulator or device that you’re using, and then press F5 to run the app.

3-solution-platforms

By default, Visual Studio uses the Clang toolchain to compile for Android. The app should build and run successfully, and you should see the app changing colors in the background. This article Create an Android Native Activity App discusses the Native Activity project in more details.

Build an OpenGLES Application on Android and iOS

The OpenGL ES Application project template under Visual C++->Cross Platform node is a good starting point for a mobile app targeting both Android and iOS. OpenGL ES (OpenGL for Embedded Systems or GLES) is a 2D and 3D graphics API that is supported on many mobile devices. This template creates a simple iOS app and an Android Native Activity app which has C++ code in common that uses OpenGL ES to display the same animated rotating cube on each platform.

4-opengles-template

The created OpenGL ES Application solution includes three library projects in the Libraries folder, one for each platform and the other one for shared C++ code, and two application projects for Android and iOS respectively.

5-solution-explorer

Now let’s run this app on both Android and iOS.

Build and run the app on Android

The solution created by the template sets the Android app as the default project. Just like run the Android Native Activity app we discussed earlier, in the Solution Platforms dropdown, select the right architecture that matches the Android emulator or device that you’re using, and then press F5 to run the app. The OpenGL ES app should build and run successfully and you will see a colored 3D spinning cube.

Build and run the app on iOS

The iOS project created in the solution can be edited in Visual Studio, but because of licensing restrictions, it must be built and deployed from a Mac. Visual Studio communicates with a remote agent running on the Mac to transfer project files and execute build, deployment, and debugging commands. You can setup your Mac by following instructions Install And Configure Tools to Build using iOS.

Once the remote agent is running on the Mac and Visual Studio is paired to it, we can build and run the iOS app. In the Solution Platforms dropdown in Visual Studio, choose the right architecture for the iOS simulator (x86) or the iOS device. In Solution Explorer, open the context menu for the OpenGLESApp1.iOS.Application project and choose Build. Then choose iOS Simulator on the toolbar to run the app in the iOS Simulator on your Mac. You should see the same colored 3D spinning cube in the iOS Simulator.

6-ios-simulator

This article Build an OpenGL ES Application on Android and iOS includes more details about the OpenGLES project.

Visual Studio to target all mobile platforms

If you’re building an app to target multiple mobile platforms (Android, iOS, UWP) and wish to share the common code in C++, you can achieve this by having one single Visual Studio solution and leverage the same code-authoring and debugging experience all in the same IDE. With Visual Studio, you can easily share and re-use your existing C++ libraries through the shared project component to target multiple platforms. The following screenshot shows a single solution with 4 projects, one for each mobile platform and one shared project for common C++ code.

7-shared-project

To learn more, please refer to how Half Brick makers of popular mobile games Fruit Ninja and Jetpack Joyride use Visual Studio for a C++ cross-platform mobile development experience.

Write cross-platform C++ code with the full power of Visual Studio IDE

With Visual Studio, you can write cross-platform C++ code using the same powerful IntelliSense and code navigation features, making code writing much more efficient. These editing capabilities not only light up in the common code, but are context-aware of the target platform when you write platform-specific code.

Member list and Quick Info, as shown in the following screenshot, are just two examples of the IntelliSense features Visual Studio offers. Member list shows you a list of valid members from a type or namespace. Typing in “->” following an object instance in the C++ code will display a list of members, and you can insert the selected member into your code by pressing TAB, or by typing a space or a period. Quick Info displays the complete declaration for any identifier in your code. IntelliSense is implemented based on the Clang toolchain when targeting the Android platform. In the following screenshot, Visual Studio is showing a list of the available Android-specific functions when the Android Native Activity project is active.

8-editing

Auto-complete, squiggles, reference highlighting, syntax colorization, code snippets are some of the other useful productivity features to be of great assistance in code writing and editing.

Navigating in large codebases and jumping between multiple code files can be a tiring task. Visual Studio offers many great code navigation features, including Go To Definition, Go To Line/Symbols/Members/Types, Find All References, View Call Hierarchy, Object Browser, and many more, to boost your productivity.

The Peek Definition feature, as shown in the following screenshot, brings the definition to the current code file, allows viewing and editing code without switching away from the code that you’re writing. You can find Peek Definition by opening the context menu on right click or shortcut Alt+F12 for a method that you want to explore. In the example in the screenshot, Visual Studio brings in the definition of __android_log_print method that is defined in the Android SDK log.h file as an embedded window into the current cpp file, making reading and writing Android code more efficiently.

9-peek-definition

Debug C++ code with the world-class Visual Studio debugger

Troubleshooting issues in the code can be time-consuming. Use the Visual Studio debugger to help find and fix issues faster. Set breakpoints in your Android C++ code and press F5 to launch the debugger. When the breakpoint is hit, you can watch the value of variables and complex expressions in the Autos and Watch windows as well as in the data tips on mouse hover, view the call stack in the Call Stack window, and step in and step out of the functions easily. In the example in the screenshot below, the Autos window is showing value changed in the Android sensorManager and accelerometerSensor types.

10-debugging

The Android debugging experience in Visual Studio also supports for debugging pre-built Android application via other IDE(s), other basic debugger capabilities (tracepoints, conditional breakpoints) and advanced features such as debugger visualizations (Natvis Support) and attaching to a running Android application as well.

You can find more information about the C++ debugger in this blog post C++ Debugging and Diagnostics.

Java debugging and language support for Android

Whether you’re writing Java or C++ code in your Android apps, Visual Studio has it covered. Visual Studio includes a Java Debugger that enables debugging Java source files in your Android projects, and with the Visual Studio Java Language Service for Android extension, you can also take advantage of the  IntelliSense and browsing capabilities for Java files in the Visual Studio IDE.

Editing Java code

First, install the Visual Studio Java Language Service for Android extension. It provides colorization (both syntactic and semantic), error and warning squiggles as well as code outlining and semantic highlighting in your Java files. You will also get IntelliSense assistance, such as Member List, Parameter Help, Quick Info, making writing Java code more efficient. In the following screenshot, Visual Studio provides a member list for the android.util.Log class.

11-java-editing

Another handy feature for larger codebases or for navigating 3rd party libraries for which you have the source code available is Go to definition (F12) which will take you to the symbol definition location if available.

Debugging Java code

To turn on Java debugging for your Android projects in your next debugging session, in the Debug Target toolbar, change Debug Type dropdown to “Java Only” as shown in the following screenshot.

12-java-setting

Now you can set line breakpoints, including conditions or hit counts for the breakpoints, anywhere in the Java code. When a breakpoint is hit, you can view variables in the Locals and Autos window, see call stack in the Call Stack window, and check log output in the Logcat window.

13-java-debugging

Blog post Java debugging and language support in Visual Studio for Android has more details on this topic.

Build Xamarin Android Native Applications

Xamarin is a popular cross-platform solution for creating rich native apps using C# across mobile platforms while maximizing code reuse. With Xamarin, you could create apps with native user interfaces and get native performance on each mobile platform. If you want to leverage Xamarin for writing user interfaces in C# while re-using your existing C/C++ libraries, Visual Studio fully supports building and debugging Xamarin Android apps that reference C++ code. This blog post Developing Xamarin Android Native Applications describes this scenario in more details.

Referencing C++ libraries in Xamarin iOS apps can be achieved by following this blog post Calling C/C++ libraries from Xamarin code.

Try out Visual Studio 2017 for mobile development with C++

Download Visual Studio 2017, try it out and share your feedback. For problems, let us know via the Report a Problem option in the upper right corner of the VS title bar. Track your feedback on the developer community portal. For suggestions, let us know through UserVoice.

C++ Unit Testing in Visual Studio

$
0
0

Testing is an increasingly important part of a software development workflow. In many cases, it is insufficient to test a program simply by running it and trying it out – as the scope of the project gets more involved, it becomes increasingly necessary to be able to test individual components of the code on a structured basis. If you’re a C++ developer and are interested in unit testing, you’ll want to be aware of Visual Studio’s unit testing tools. This post goes through just that, and is part of a series aimed at new users to Visual Studio.
This blog post goes over the following concepts:

  1. Setting Up Unit Testing
  2. The Microsoft Native C++ Unit Test Framework
  3. Using the Test Explorer to Run Tests in the IDE
  4. Determining Unit Test Code Coverage

Setting Up Unit Testing

The easiest and most organized way to set up unit tests is to create a separate project in Visual Studio for your tests. You can create as many test projects as you want in a solution and connect them to any number of other Visual Studio projects in that solution that contain the code you want to test. Assuming you already have some code that you want to test, simply follow these steps to get yourself set up:

  1. Right-click your solution and choose Add > New > Project. Click the Visual C++ category, and choose the Test sub-category. Select Native Unit Test Project, give the project a descriptive name, and then click OK.
    New Project Wizard for Testing
  2. Visual Studio will create a new project containing unit tests, with all dependencies to the native test framework already set up. The next thing to do is to add references to any projects that will be tested. Right-click the unit test project and choose Add > Reference…
    Right-click Add > Reference
  3. Check any projects that you want to unit test from your test project, and then press OK.
    Add > Reference
    Your unit testing project can now access your project(s) under test. You can now start writing tests, as long as you add #include statements for the headers you want to access.

NOTE: You will only be able to unit test public functions this way. To unit test private functions, you must write your unit tests in the same class as the code that is being tested.

The Microsoft Native C++ Unit Test Framework

Visual Studio ships with a native C++ test framework that you can use to write your unit tests. The framework defines a series of macros to provide simplified syntax.

If you followed the steps in the previous procedure, you should have a unit test project set up along with your main code. Open unittest1.cpp in your test project and look at the starting code provided:
Starting code provided when creating MSTest project.
Right from the start, you’ll notice that dependencies have already been set up to the test framework, so you can get to work writing your tests. Assuming you connected your test project to your project(s) under test via Add > Reference earlier, you can simply add the #include statements for the header files of the code you want to test.

Tests can be organized by using the TEST_CLASS and TEST_METHOD macros, which perform exactly the functions you’d expect. A TEST_CLASS is a collection of related TEST_METHODS, and each TEST_METHOD contains a test. You can name your TEST_CLASS and TEST_METHOD anything you want in the brackets. It’s a good idea to use descriptive names that make it easy to identify each test/test group individually later.

Let’s try writing some basic asserts. At the TODO comment, write:
Assert::AreEqual(1, 1);

This is a basic equality assert which compares two expressions. The first expression holds the expected value, the second holds the item you are testing. For the Assert to pass, both sides must evaluate to the same result. In this trivial example, the test will always pass. You can also test for values you don’t want your expression to evaluate to, like this:
Assert::AreNotEqual(1, 2);

Here, for the test to pass, the two expressions must not evaluate to the same result. While this kind of assert is less common, you may find it useful for verifying edge cases where you want to avoid a specific behavior from occurring.

There are several other Assert functions that you can try. Simply type Assert:: and let IntelliSense provide the full list to take a look. Quick Info tooltips appear for each Assert as you make a selection in the list, providing more context on their format and function. You can find a full reference of features in the Microsoft C++ native framework on MSDN.

Using the Test Explorer to Run Tests in the IDE

With Visual Studio, you’re not restricted to running unit tests in the command line. The Text Explorer window in Visual Studio provides a simple interface to run, debug, and parallelize test execution.
Test Explorer window
This is a straightforward process. Once you connect your test project to your project(s) under test, add some #include directives in the file containing your unit tests to the code under test, and write some Asserts, you can simply run a full build. Test Explorer will then discover all your unit tests and populate itself with them.

NOTE: In .NET, a feature called Live Unit Testing is available. This feature is not currently supported in C++, so unit tests are discovered and executed only after you run builds.

To run your unit tests, simply click the Run All link in the Test Explorer. This will build your project (though this process is skipped if the project is already up to date) then run all your tests. The Test Explorer indicates the passing tests with a checkmark and the failing tests with an X. A summary of execution results is provided at the bottom of the window. You can click on any failing unit test to see why it failed, including any exceptions that may have been thrown. Execution times for each unit test are also provided. For realistic test execution times, test in the Release solution configuration rather than Debug, which will provide faster runtimes which are more approximate to your shipped application.

To be able to debug your code as you run your unit tests (so you can stop at breakpoints and so forth), simply use the Test > Debug menu to run your tests.

Determining Unit Test Code Coverage

If you are using Visual Studio Enterprise, you can run code coverage on your unit tests. Assuming you have unit tests already set up for your project, this is as simple as going to Test > Analyze Code Coverage in the main Visual Studio menu at the top of the IDE. This opens the Code Coverage Results window which summarizes code coverage data for your tests.
Code Coverage Results window
NOTE: There is a known issue where Code Coverage will not work in C++ unless /DEBUG:FULL is selected as the debugging configuration. By default, the configuration is set to /DEBUG:FASTLINK instead. You can switch to /DEBUG:FULL by doing the following:

  1. Right-click the test project and choose Properties.
  2. Go to Linker > Debugging > Generate Debug Info.
  3. Set the option to Generate Debug Information optimized for sharing and publishing (/DEBUG:FULL).

The Code Coverage Results window provides an option called Show Code Coverage Coloring, which colors the code based on whether it’s covered or not.
Code Coverage coloring
Code coverage is counted in blocks, with a block being a piece of code with exactly one entry and exit point. If a block is passed through at least once, it is considered covered.

For more information on C++ unit testing, including some more advanced topics, check out the following MSDN articles:

C++ Code Editing and Navigation in Visual Studio

$
0
0

Visual Studio comes packed with a set of productivity tools to make it easy for C++ developers to read, edit, and navigate through their code. In this blog post we will dive into these features and go over what they do. This post is part of a series aimed at new users to Visual Studio.

This blog post goes over the following concepts:

  1. Reading and Understanding Code
  • Navigating Around Your Codebase
  • Authoring and Refactoring Code
  • Keyboard Shortcut Reference
  • Conclusion
  • Reading and Understanding Code

    If you’re like most developers, chances are you spend more time looking at code than modifying it. With that in mind, Visual Studio provides a suite of features to help you better visualize and understand your project.

    Basic Editor Features

    Visual Studio automatically provides syntax colorization for your C++ code to differentiate between different types of symbols. Unused code (e.g. code under an #if 0) is more faded in color. In addition, outlines are added around code blocks to make it easy to expand or collapse them.
    Basic editor features
    If there is an error in your code that will cause your build to fail, Visual Studio adds a red squiggle where the issue is occurring. If Visual Studio finds an issue with your code but the issue wouldn’t cause your build to fail, you’ll see a green squiggle instead. You can look at any compiler-generated warnings or errors in the Error List window.
    Error List window
    If you place your cursor over a curly brace, ‘{‘ or ‘}’, Visual Studio highlights its matching counterpart.

    You can zoom in or out in the editor by holding down Ctrl and scrolling with your mouse wheel or selecting the zoom setting in the bottom left corner.
    Zooming in Visual Studio editor

    The Tools > Options menu is the central location for Visual Studio options, and gives you the ability to configure a large variety of different features. It is worth exploring to tailor the IDE to your unique needs.
    Configuring settings in Visual Studio via Tools > Options
    You can add line numbers to your project by going to 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++.

    Quick Info and Parameter Info

    You can hover over any variable, function, or other code symbol to get information about that symbol. For symbols that can be declared, Quick Info displays the declaration.
    Quick Info tooltip example
    When you are writing out a call to a function, Parameter Info is invoked to clarify the types of parameters expected as inputs. If there is 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.
    Quick Info tooltip displaying an error in Visual Studio
    In addition, Quick Info displays any comments that you place just above the definition of the symbol that you hover over, giving you an easy way to check the documentation in your code.

    Scroll Bar Map Mode

    Visual Studio takes the concept of a scroll bar much further than most applications. With Scroll Bar Map Mode, you can scroll and browse through a file at the same time without leaving your current location, or click anywhere on the bar to navigate there. Even with Map Mode off, the scroll bar highlights changes made in the code in green (for saved changes) and yellow (for unsaved changes). You can turn on Map Mode in Tools > Options > Text Editor > All Languages > Scroll Bars > Use map mode for vertical scroll bar or by searching for “map” with Quick Launch (Ctrl + Q).
    Using Scroll Bar Map Mode to view your code file at a glance

    Class View

    There are several ways of visualizing your code. One example is Class View. You can open Class View from the View menu or by pressing Ctrl + Shift + C. 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).
    The Class View window

    Generate Graph of Include Files

    To understand dependency chains between files, right-click while in any open document and choose Generate graph of include files.
    Generate Graph of Include Files feature
    You also have the option to save the graph for later viewing.

    View Call Hierarchy

    You can right-click any function call to view a recursive list of its call hierarchy (both functions that call it, and functions that it calls). Each function in the list can be expanded in the same way. For more information, see Call Hierarchy.
    View Call Hierarchy feature

    Peek Definition

    You can check out the definition of a variable or function at a glance, inline, by right-clicking it and choosing Peek Definition, or pressing Alt+F12 with the cursor over that symbol. This is a quick way to learn more about the symbol without having to leave your current position in the editor.
    Use Peek Definition to get a quick look at where and how a code symbol is defined.

    Navigating Around Your Codebase

    Visual Studio provides a suite of tools to allow you to navigate around your codebase quickly and efficiently.

    Open Document

    Right-click on an #include directive in your code and choose Open Document, or press Ctrl+Shift+G with the cursor over that line, to open the corresponding document.

    Toggle Header/Code File

    You can switch between a header file and its corresponding source file or vice versa, by right-clicking anywhere in your file and choosing Toggle Header / Code File or by pressing its corresponding keyboard shortcut: Ctrl+K, Ctrl+O.

    Solution Explorer

    Solution Explorer is the primary means of managing and navigating between files in your solution. You can navigate to any file by clicking it in Solution Explorer. By default, files are grouped by the projects that they appear in. To change this default view, click the Solutions and Folders button at the top of the window to switch to a folder-based view.
    Solution Explorer window

    Go To Definition/Declaration

    You can navigate to the definition of a code symbol by right-clicking it in the editor and choosing Go To Definition, or pressing F12. You can navigate to a declaration similarly from the right-click context menu, or by pressing Ctrl+F12.
    Navigating to a definition or declaration via the editor context menu

    Find / Find in Files

    You can run a text search for anything in your solution with Find (Ctrl+F) or Find in Files (Ctrl+Shift+F).

    Find can be scoped to a selection, the current document, all open documents, the current project, or the entire solution, and supports regular expressions. It also highlights all matches automatically in the IDE.
    Find (Ctrl + F)
    Find in Files is a more sophisticated version of Find that displays a list of results in the Find Results window. It can be configured even further than Find, such as by allowing you to search external code dependencies, filter by filetypes, and more. You can organize Find results in two windows or append results from multiple searches together in the Find Results window. Individual entries in the Find Results window can also be deleted if they are not desired.
    Find in FilesFind Results window

    Find All References

    Find All References displays a list of references to the chosen symbol. For more information on Find All References, check out our blog post, Find All References Re-designed for Larger Searches.

    Navigation Bar

    You can navigate to different symbols around your codebase by using the navbar that is above the editor window.
    navbar

    Go To

    Go To (Ctrl + T) is a code navigation feature that can be used to navigate to files, code symbols or line numbers. For more information, take a look at Introducing Go To, the Successor to Navigate To.

    Quick Launch

    Quick Launch makes it easy to navigate to any window, tool, or setting in Visual Studio. Simply type Ctrl+Q or click on the search box in the top-right corner of the IDE and search for what you are looking for.
    Quick Launch search feature

    Authoring and refactoring code

    Visual Studio provides a suite of tools to help you author, edit, and refactor your code.

    Basic Editor Features

    You can easily move lines of code up and down by selecting them, holding down Alt, and pressing the Up/Down arrow keys.

    To save a file, press the Save button at the top of the IDE, or press Ctrl+S. Generally though, it’s a good idea to save all your changed files at one time by using Save All (Ctrl+Shift+S).

    Change Tracking

    Any time you make a change to a file, a yellow bar appears on the left to indicate that unsaved changes were made. When you save the file, the bar turns green.
    Change tracking in the editor
    The green and yellow bars are preserved as long as the document is open in the editor. They represent the changes that were made since you last opened the document.

    IntelliSense

    IntelliSense is a powerful code completion tool that suggests symbols and code snippets for you as you type. C++ IntelliSense in Visual Studio runs in real time, analyzing your codebase as you update it and providing contextual recommendations based on the characters of a symbol that you’ve typed. As you type more characters, the list of recommended results narrows down.
    How IntelliSense works in Visual Studio
    In addition, some symbols are omitted automatically to help you narrow down on what you need. For example, when accessing a class object’s members from outside the class, you will not be able to see private members by default, or protected members (if you are not in the context of a child class).

    After you have picked out the symbol you want to add from the drop-down list, you can autocomplete it with Tab, Enter, or one of the other commit characters (by default: {}[]().,:;+-*/%&|^!=?@#\).

    TIP: If you want to change the set of characters that can be used to complete IntelliSense suggestions, search for “IntelliSense” in Quick Launch (Ctrl + Q) and choose the Text Editor -> C/C++ -> Advanced option to open the IntelliSense advanced settings page. From there, edit Member List Commit Characters with the changes you want. If you find yourself accidentally committing results you didn’t want or want a new way to do so, this is your solution.
    IntelliSense Advanced Settings
    The IntelliSense section of the advanced settings page also provides many other useful customizations. The Member List Filter Mode option, for example, has a dramatic impact on the kinds of IntelliSense autocomplete suggestions you will see. By default, it is set to Fuzzy, which uses a sophisticated algorithm to find patterns in the characters that you typed and match them to potential code symbols. For example, if you have a symbol called MyAwesomeClass, you can type “MAC” and find the class in your autocomplete suggestions, despite omitting many of the characters in the middle. The fuzzy algorithm sets a minimum threshold that code symbols must meet to show up in the list.

    If you don’t like the fuzzy filtering mode, you can change it to Prefix, Smart, or None. While None won’t reduce the list at all, Smart filtering displays all symbols containing substrings that match what you typed. Prefix filtering on the other hand purely searches for strings that begin with what you typed. These settings give you many options to define your IntelliSense experience, and it’s worth trying them out to see what you prefer.

    IntelliSense doesn’t just suggest individual symbols. Some IntelliSense suggestions come in the form of code snippets, which provide a basic example of a code construct. Snippets are easily identified by the square box icon beside them. In the following screenshot, “while” is a code snippet that automatically creates a basic while loop when it is committed. You can choose to toggle the appearance of snippets in the advanced settings page.
    Code snippet for while loop
    Visual Studio 2017 provides two new IntelliSense features to help you narrow down the total number of autocomplete recommendations: Predictive IntelliSense, and IntelliSense filters. Check out our blog post, C++ IntelliSense Improvements – Predictive IntelliSense & Filtering, to learn more about how these two features can improve your productivity.

    If you ever find yourself in a situation where the list of results suggested by IntelliSense doesn’t match what you’re looking for, and you already typed some valid characters beforehand, you can choose to unfilter the list by clicking the Show more results button in the bottom left corner of the drop-down list–which looks like a plus (+)—or by pressing Ctrl + J. This will refresh the suggestions, and add some new entries. If you’re using Predictive IntelliSense, which is an optional mode that uses a stricter filtering mechanism than usual, you may find the list expansion feature even more useful.

    Quick Fixes

    Visual Studio sometimes suggests ways to improve or complete your code. This comes in the forms of some lightbulb pop-ups called Quick Fixes. For example, if you declare a class in a header file, Visual Studio will suggest that it can declare a definition for it in a separate .cpp file.
    Quick Fixes

    Refactoring Features

    Do you have a codebase that you’re not happy with? Have you found yourself needing to make sweeping changes but are afraid of breaking your build or feel like it will take too long? This is where the C++ refactoring features in Visual Studio come in. We provide a suite of tools to help you make code changes. Currently, Visual Studio supports the following refactoring operations for C++:

    • Rename
    • Extract Function
    • Change Function Signature
    • Create Declaration/Definition
    • Move Function Definition
    • Implement Pure Virtuals
    • Convert to Raw String Literal

    Many of these features are called out in our announcement blog post, All about C++ Refactoring in Visual Studio. Change Function Signature was added afterward, but functions exactly as you’d expect – it allows you to change the signature of a function and replicate changes throughout your codebase. You can access the various refactoring operations by right-clicking somewhere in your code or using the Edit menu. It’s also worth remembering Ctrl + R, Ctrl + R to perform symbol renames; it’s easily the most common refactoring operation.

    In addition, check out the C++ Quick Fixes extension, which adds a host of other tools to help you change your code more efficiently.

    For additional information, check our documentation on Writing and refactoring code in C++.

    Code Style Enforcement with EditorConfig

    Visual Studio 2017 comes with built-in support for EditorConfig, a popular code style enforcement mechanism. You can create .editorconfig files and place them in different folders of your codebase, applying code styles to those folders and all subfolders below them. An .editorconfig file supersedes any other .editorconfig files in parent folders and overwrites any formatting settings configured via Tools > Options. You can set rules around tabs vs. spaces, indent size, and more. EditorConfig is particularly useful when you are working on a project as part of a team, such as when a developer wants to check in code formatted with tabs instead of spaces, when your team normally uses spaces. EditorConfig files can easily be checked in as part of your code repo to enforce your team style.

    Learn more about EditorConfig support in Visual Studio

    Keyboard Shortcut Reference

    For a full set of default key bindings for Visual Studio C++ developers, take a look at our Visual Studio 2017 Keyboard Shortcut Reference.

    Conclusion

    Lastly, you can find additional resources on how to use Visual Studio in our official documentation pages at docs.microsoft.com. In particular, for developer productivity, we have the following set of articles available:

    Getting Started with Visual Studio for C and C++ Development

    $
    0
    0

    Are you new to Visual Studio and working with C++? Then you’ve come to the right place. Whether you’re a student writing one of your first programs or a seasoned C++ developer with years of experience, you’ll find Visual Studio to be a powerful environment for C++ development. Visual Studio is an IDE packed with features, from code browsing, colorization and navigation, to autocompletion of symbols, a built-in compiler and build system, a top of the line debugger, and built-in testing and code analysis tools. We have you covered from beginning to end, from code inception to continuous integration management, but of course this means there is a lot to learn. This blog post breaks down the basics to get you started. You will get only a small glimpse of the powerful tools that Visual Studio provides, but if you want to learn more, you should click the links throughout this post.

    This blog post goes over the following concepts:

    1. Setting Up Visual Studio
    2. Opening Projects or Folders of Code
    3. Building the Application
    4. Code Editing & Navigation
    5. Debugging and Diagnosing Issues
    6. Testing
    7. Working With A Team
    8. Other Topics
    9. Conclusion

    Setting Up Visual Studio

    Visual Studio crossed the 20-year mark with the release of Visual Studio 2017. There are many versions of the product out there, but in general, you should always pick the latest one. This will allow you to use the latest and greatest features, including the most up-to-date compiler. You’ll also benefit from recent bug fixes and performance improvements.

    Visual Studio is available in three different editions: Community, Professional, and Enterprise. The Community Edition is completely free of charge for small businesses, open source projects, academic research, and classroom learning environments. If you don’t qualify for the Community License, you can purchase the Professional Edition instead. If you work for a large enterprise or simply want the best Visual Studio has to offer, then you should consider the Enterprise Edition. You can compare the offerings on the Visual Studio website if you are unsure. This guide is applicable to all editions.

    Download the latest Visual Studio

    Once you have downloaded the installer, run it. Visual Studio allows you to choose what workloads you want to install, choosing only the components you want, and nothing you don’t. The following workloads are under the C++ umbrella:

    Desktop Workload Icon Desktop development with C++
    Provides the tools needed for building and debugging classic desktop applications. This includes classic Win32 console applications.
    Mobile Workload Icon Mobile development with C++
    Includes the tools needed for targeting Android and iOS.
    Game Workload Icon Game development with C++
    Enables you to quickly and easily get started building games using DirectX, Unreal Engine, or Cocos2d.
    Linux Workload Icon Linux development with C++
    All the necessary tools for developing and debugging Linux applications.
    UWP Workload Icon Universal Windows Platform development
    This workload is not specific to just C++, but you can enable the C++ support by checking the individual component for “C++ UWP support”.

    There are a variety of other workloads for other languages such as C#, and other platforms such as Microsoft Azure (for your cloud needs). The workloads you install are not permanent, and you can always change these options by opening the installer and selecting Modify.

    For this guide, please install the Desktop development with C++ workload.
    Installer Workloads

    Once you have made your selection and clicked Install, Visual Studio will begin the installation process. Once it is complete, Visual Studio is all set up and ready to go!

    Now let’s look at an actual project. For this next section, if at any time, you cannot find some feature or command that you are looking for, you can search for it via Quick Launch, the search box at the upper right of the IDE (or press Ctrl+Q to get there fast).

    Download the demo project

    Opening Projects or Folders of Code

    If you open the demo project folder in Windows File Explorer, you will find a variety of different files in addition to some source code. Generally, code organized by Visual Studio appears as a Solution, which contains a collection of Projects. When a codebase is organized this way, it includes a .sln file (which configures the solution) as well as .vcxproj files (which configure each project); these files help define things like include paths, compiler settings, and how the projects are connected.

    Visual Studio also supports an Open Folder mode as of Visual Studio 2017 which does away with .sln and .vcxproj files and allows you as the user to configure your own environment independently. This approach is ideal for cross-platform projects that will be run from a variety of different IDEs or editors. Better yet, if you are a CMake user, as of Visual Studio 2017 there is a built-in CMake experience. This guide will not go over Open Folder or CMake, but you are encouraged to check out the relevant blog posts linked in this paragraph for more information.

    To open demoApplication, double click the .sln file, or from Visual Studio go to File > Open > Project/Solution… and navigate to the appropriate solution.

    Once you have opened the project, a view of the content in the project will appear in the Solution Explorer, pictured below:Solution Explorer Window
    New projects can be also created by going to File > New > Project… and selecting the template that is appropriate. Console applications are under Visual C++ > Win32.

    Building the Application

    Visual Studio is closely integrated with the Visual C++ compiler, which makes it easy to build and debug your C++ applications. Near the top of the IDE inside the standard toolbar, there are dropdowns where you can change your build configuration and architecture. You can also easily add more configurations, as needed. For this exercise, you can leave the default settings of Debug and x86.
    Project Configuration
    Attempt to build the application by going to Build > Build Solution (or alternatively by pressing F7). The build will fail, since the code contains an error.
    The Output Window is a valuable tool while you are building; it provides information about the status of the build.
    Output Window

    Fixing compiler errors

    You should see an error in the Error List at the bottom of the screen when you attempt to build. With this error, you not only get the location of the problem and a description, but if you double-click the line, you will be brought to the specific location in the code. This makes it easy to quickly navigate to problem areas.

    Double-click on the error after building, and fix the offending line of code.

    Code Editing & Navigation

    This section provides a glimpse of what is possible in Visual Studio. To learn more about this area please visit the C++ Code Editing and Navigation in Visual Studio blog post.

    Intellisense

    One of the most useful features for helping you write code quickly in Visual Studio is IntelliSense, which is a context-aware code completion tool. As you type, Visual Studio will suggest classes, methods, objects, code snippets, and more symbols that make sense in relation to what you have typed so far and where you have typed it. You can scroll up and down the suggestions with the arrow keys, and complete symbols with Tab.

    In the main function try adding a call to the farewell function to the mySorter object. You should see IntelliSense pop up with all the possible functions available from the sorter class.
    IntelliSense

    Go To

    To efficiently write and understand code, easy code navigation is essential. By using the Go To feature (Ctrl+T) you can quickly get to where you need to go, without taking your hands off the keyboard. When you open the dialog, you can filter your results by clicking on the desired button, or by starting your query with a specific token. For example, you can go to a specific file by opening the Go To dialog and typing “f ”. Another common way to access this dialog is by going to a specific line number; you can do this by opening the menu traditionally and using the “:” token, or by pressing Ctrl+G. Try using Go To to navigate around the demo project.

    Use the Go To menu (Ctrl+T) to open the file sorter.h by typing “f sorter.h”.
    Use the Ctrl+G shortcut to go to line 23 to change the private member “name” to your name.

    Go To

    Peek/Go to Definition

    Sometimes it can be challenging to find out where a function or object is defined in your codebase. This problem is easily solved in Visual Studio, where you can easily peek into definitions. Try this in the demo project by selecting the function you want to look at, and pressing Alt+F12, or selecting it from the right-click menu. This will bring up a preview of the file where the function is defined, where you can quickly make small edits. Press Esc to close the preview window. You can also go directly to the definition by pressing only F12.

    Use Peek Definition on the printVector function by selecting the function and pressing Alt+F12.

    Add a dash between the numbers in the vector when they are printed.
    Peek Definition Window

    Rename

    You can also use Visual Studio to refactor existing code. In the demo project, there is a function that has an unhelpful name. Rather than going to each file to change the name of each occurrence manually, choose one of the functions and press Ctrl+R, Ctrl+R or right-click it and choose Rename. This will bring up a menu where you can choose what you want to rename it to, and then preview the changes before they are committed.

    Use Rename (Ctrl+R, Ctrl+R) to change the method “SILLY_SALUTATION_FUNCTION” to something more useful, such as “greeting”.
    Rename Refactoring Operation

    Debugging and Diagnosing Issues

    Once you can successfully build your application and write code easily, the next step is often debugging the application. Debugging can be a complex process, and Visual Studio provides many powerful tools to help along the way. The most commonly used debugging tool is the breakpoint, so let’s start with that. If you click on the bar to the left of your code, a red circle should appear. If you click the circle, the breakpoint will be removed.
    Breakpoint
    When a breakpoint is set and the program reaches that point of execution, it will stop, allowing you to inspect variables and the current state of the program.

    Place a breakpoint on line 33 of demoApplication.cpp by clicking the bar to the left of the line numbers.

    Click the red circle again to remove the breakpoint.
    Start Debugging
    To begin debugging, you can either press the green arrow at the top of the IDE or press F5. Once the program has stopped on the breakpoint, there are many things you can do to help you diagnose problems. One of the best ways to find problems is to understand the current state of the program, versus what it should be. This can be easily achieved by using the Autos Window, which lists recently used variables and their values. You can also hover your mouse over a variable to see what the current value is.

    Do the following:

    1. Place a breakpoint on line 14 of the main function.
    2. Click the green arrow at the top of the IDE or press F5 to begin debugging.
    3. Find out what the value of testInt is before it is initialized by hovering over the value in the code.
    4. Look at the value of testInt in the Autos window.
    5. Press the green arrow or F5 again to stop debugging.


    Breakpoint Stop
    Autos Window
    When you have sufficiently understood the current state of the program, you can press the green arrow button or press F5 again to have the program run until the next breakpoint. You can also step the program one line at a time if needed by using the arrows at the top.
    Stepping
    Step Over (F10) will run through whatever is on the current line, and suspend execution after the function returns. Step Into (F11) will follow the function call of the next line, allowing you to see what is happening inside that function. At any time, you can step out (Shift+F11), which will place the program just after it has completed the current functional scope. Once you are finished debugging you can run the program to its completion, or press the red square (or Shift+F5) at the top of the IDE to stop the debugging session.

    Use a combination of these to explore the demo project and see if you can fix the runtime bug in the sort algorithm (Hint: it is in the sort algorithm itself).

    There are many more tools within Visual Studio that can help you profile and debug your applications. Check out the C++ Debugging and Diagnostics blog post to learn more.

    Testing

    Visual Studio has a built-in test framework to help you unit test your projects, ensuring that the code you write is working as expected. To test the demo project, which is a native console application, you can add a Native Unit Test Project to the solution.

    Add a test project to the demo. This is done by going to File > New > Project then selecting Visual C++ > Test > Native Unit Test Project. Make sure to choose the Add to solution option in the Solution dropdown. You can also simply right-click your solution name in the Solution Explorer and choose Add > New Project to accomplish the same task.
    Create Test Project
    Once you have added a unit test, you can open the .cpp file and see the basic testing skeleton in the template, and begin to add tests.

    Add a test method, making sure that it will pass. Try the following code:
    TEST_METHOD(TestMethod1)
    {
    Assert::AreEqual(1,1);
    }

    Writing An Assert
    Once you have added a test, you can run the test by going to Test > Run > All Tests in the menu at the top of the IDE. Once you have run the tests, you will see the results in the Test Explorer window.

    Run your test by going to Test > Run > All Tests. Try adding another test that will fail, and running the tests again.
    Test Explorer Window
    If you would like to find out more information about unit testing, including how to connect your test project to your code under test, and check the code coverage of your unit tests, check out the C++ Unit Testing in Visual Studio blog post.

    Working with A Team

    It is very common these days to be working on a project with a team, and Visual Studio makes collaboration with others easy! You can easily create new source control repositories using Git or Team Foundation Server to manage your codebase. To create a new repo for a project, click the Add to Source Control button at the bottom of the screen, and add the opened project to the source control system of your choice.
    Add to Source Control
    Once you do that, a local repository will be made for your project. From here you can make commits, or push your changes to a remote Git service such as GitHub. This is all managed in the Team Explorer window.
    Team Explorer Window

    Try adding the demo project to source control, and pushing it to GitHub. This is done by pressing the Add to source control button, and then pushing to a remote repository inside the Team Explorer.

    You can also very easily clone from source control from the Team Explorer window. Choose Projects > New Repository, and then follow the prompts to clone the project. From here, all you must do is paste in the URL, and the project will be cloned.
    Clone Project
    Clone Project
    To learn more about working on a project as a team in Visual Studio, check out the Visual Studio for Teams of C++ Developers blog post.

    Other Topics

    There are many other useful things Visual Studio can do. So many things, in fact, it is hard to cover it all in one guide. Follow the links below to find out more on how to get the most out of Visual Studio.

    Code Analysis

    Visual Studio by default catches a lot of code issues, but its Code Analysis tool can often uncover hard-to-find issues that would normally be missed. Common errors that are reported include buffer overflows, uninitialized memory, null pointer dereferences, and memory and resource leaks. This functionality is built into the IDE, and can easily be used to help you write better code. Try it out by going to the Analyze menu and choosing Run Code Analysis > On Solution. Learn more about Code Analysis as well as the C++ Core Guidelines Checkers in the announcement blog post.

    Library Acquisition

    Library acquisition in C++ can be challenging. While Visual Studio has support for NuGet package management, more recently a new tool called vcpkg was launched. Vcpkg is an open source tool maintained by Microsoft that simplifies acquiring and building open source libraries, with over 200 currently supported. This tool, while separate from Visual Studio itself, is a valuable companion for any C++ developer on Windows. Check out the announcement blog post for details.

    Conclusion

    We hope that this guide has allowed you to get up to speed with Visual Studio quickly, and that you have learned some of the core functionality. This should be enough to get you started, but there are still many more features that could not be covered in this guide. The Visual C++ Blog is a very useful resource to find out more about not only the product overall, but also what we are currently working on and changing. You can find the comprehensive product documentation on docs.microsoft.com as well. Now get out there and build something amazing!

    We are constantly trying to improve, so if you have any feedback or suggestions for us, please feel free to reach out to us anytime! We can be reached via email at visualcpp at microsoft.com and you can provide feedback via Help > Report A Problem in the product, or via Developer Community.

    Visual Studio Code C/C++ extension April 2017 Update

    $
    0
    0

    Earlier today we shipped the April 2017 update to the C/C++ extension for Visual Studio Code. We are excited to introduce the following new features in this update:

    • Error Squiggles
    • Quick Info
    • Go to Declaration
    • Bash on Windows debugging support

    The original blog post has been updated with these changes. If you have this extension installed already, Visual Studio Code sends a notification for the update and installs the update for you automatically. If you haven’t installed it before, download the C/C++ extension for Visual Studio Code to try it out.

    1-download

    Error Squiggles and Quick Info

    Enabling the features

    In this update, we’re shipping Error Squiggles and Quick Info as “experimental features”. What this means is that they are turned on by default only for those using VSCode Insiders, and off by default for anyone else. You can enable or disable the features by toggling the setting in the settings.json file (File->Preferences->Settings). In the settings file, search for “intellisense” to locate the C_Cpp.intelliSenseEngine setting, and set it to “Default” to enable the new IntelliSense Engine (see the following screenshot). “Default” will become the true default for everyone when these features exit their experimental state. 🙂

    2-intellisense-engine

    The “C_cpp.errorSquiggles” setting in the same file allows turning on or off the squiggle feature when the default IntelliSense engine is used.

    We encourage you to turn on the features, try them out, and send us feedback so we can further polish these features and turn them on by default soon.

    Error Squiggles

    A while back we enabled showing error squiggles for the #include statements. This update adds support for showing squiggles under any program element, including variables, keywords, and braces, if a workspace exists. In other words, squiggles are not enabled when only single files are open.

    For example, in the following screenshot, Vector3 has a red squiggly underline, indicating this type can’t be found in the specified include paths.

    3-quick-action

    Clicking on Vector3 in the code, you will see a light bulb on the left side of the line. The “Add include path to settings” menu on the light bulb will take you to the c_cpp_properties.json file in which you can specify the include paths for IntelliSense. If the c_cpp_properties.json file does not already exist, it will be created and populated with the following default include paths:

    • On Windows, we default to the workspace root, the VC include path if Visual Studio 2017 or 2015 is installed, and the latest Windows SDK if found.
    • On Linux, we default to the workspace root, the highest version of the includes found in /usr/include/c++, 64-bit specific headers if they are present, and headers found under /usr/lib/clang if present.
    • On Mac, we default to the workspace root and the Xcode default toolchain if present or the same paths as Linux if Xcode is not found.

    You can add, remove, or modify the paths in the includePath setting to fit your scenario. In this example, I added another path (highlighted with the red underline) for the IntelliSense engine to look for types.

    4-include-paths

    Note that there’s a newly-added “path” setting under “browse”, which is used by the tag parser for performing fuzzy search results. The “includePath” setting, which was formerly used by the tag parser, now controls the include paths for the new IntelliSense engine. On opening any existing c_cpp_properties.json files, the value in the “includePath” is automatically copied into the “browse.path” setting.

    You can also configure the “defines” setting in the c_cpp_properties.json file to define preprocessor symbols.

    Now if I save the change in the json file and switch back to the previous header file, the types are now resolved and the red squiggles are gone.

    Quick Info

    Quick Info enables viewing the type information or function’s signature when hovering the mouse cursor over a variable or a function. In this extension, this used to be performed by the tag parser, which provides quick but fuzzy results – sometimes inaccurate. With the new IntelliSense engine, we can provide more accurate results for local and global variables, functions, and symbols. In the following screenshot, hovering over the local variable “it” displays its accurate type information.

    5-quick-info

    Go to Declaration

    With this extension, you can already perform “Go to Definition” (F12) on variables or functions to open the document where the object is defined. This update added “Go to Declaration” (Ctrl+F12) for navigating to the file where the object is declared. To use this feature, simply right click on any variable or function and select “Go to Declaration” from the menu.

    In this example in the following screenshot, I selected “Text.DrawString” function and clicked on “Go to Declaration”.

    6-go-to-declaration

    In the next screenshot, you can see that the “TextRenderer.h” file is open and the two DrawString function declarations are being highlighted.

    7-show-declaration

    Bash on Windows debugging support

    With the release of Windows 10 Creators Update, you are now able to use VSCode and this extension to debug your Windows Subsystem for Linux (WSL) Bash on Ubuntu projects. You can use VSCode to write code on Windows, and debug through bash.exe to the Bash on Windows layer. Please see these instructions on how to use VSCode C/C++ extension to debug Windows 10’s Subsystem for Linux.

    Tell us what you think

    Download the C/C++ extension for Visual Studio Code, try it out and let us know what you think. File issues and suggestions on GitHub. If you haven’t already provided us feedback, please take this quick survey to help shape this extension for your needs.

    Vcpkg: introducing export command

    $
    0
    0

    Vcpkg helps you acquire and build open source libraries on Windows. Since September 2016, the community added more than 200 libraries in the vcpkg catalog and has been contributing actively to the code itself. Vcpkg now supports Visual Studio 2015 and Visual Studio 2017 and can target dynamic or static libraries and platforms like x64, x86 or UWP.

    Today we are delighted to announce a new command: vcpkg export. As you told us in our recent survey, there is a need for a command that exports the binaries that you built using vcpkg. The purpose of this new command is to let you share and redistribute the binaries generated using vcpkg with other developers who want to use it in their project. For example, the team responsible for 3rd party library acquisition in an enterprise can use vcpkg to generate a common set of library binaries used by enterprise projects, and then use vcpkg export to share those binaries (including the .h, the .lib and all thing needed to build against these libraries) with internal developers.

    The syntax for the new command is:

    vcpkg export <pkg1> <pkg2> ... --[options]

    You have several options for the export format:

    • –zip
    • –7zip
    • –nuget
    • –raw (uncompressed folder)

    When you specify a package to export, all its dependencies are also included in the exported archive. This means the exported packages can stand on their own – no additional dependencies are required.

    Here are some examples that demonstrate ways you can use vcpkg export.

    i. Exporting to nuget
    > vcpkg export cpprestsdk zlib --nuget
    The following packages are already built and will be exported:
    * boost:x86-windows
    * bzip2:x86-windows
    cpprestsdk:x86-windows
    * openssl:x86-windows
    * websocketpp:x86-windows
    zlib:x86-windows
    Additional packages (*) need to be exported to complete this operation.
    Exporting package zlib:x86-windows...
    Exporting package zlib:x86-windows... done
    Exporting package openssl:x86-windows...
    Exporting package openssl:x86-windows... done
    Exporting package bzip2:x86-windows...
    Exporting package bzip2:x86-windows... done
    Exporting package boost:x86-windows...
    Exporting package boost:x86-windows... done
    Exporting package websocketpp:x86-windows...
    Exporting package websocketpp:x86-windows... done
    Exporting package cpprestsdk:x86-windows...
    Exporting package cpprestsdk:x86-windows... done
    Creating nuget package...
    Creating nuget package... done
    NuGet package exported at: E:/workspace/vcpkg/vcpkg-export-20170502-150917.nupkg
    
    With a project open, go to Tools->NuGet Package Manager->Package Manager Console and paste:
    
    Install-Package vcpkg-export-20170502-150917 -Source "E:\workspace\vcpkg"
    ii. Exporting to 7zip and zip

    You can specify more than one of these options to export in multiple formats.

    > vcpkg export zlib --7zip --zip
    The following packages are already built and will be exported:
    zlib:x86-windows
    Exporting package zlib:x86-windows...
    Exporting package zlib:x86-windows... done
    Creating zip archive...
    Creating zip archive... done
    Zip archive exported at: E:/workspace/vcpkg /vcpkg-export-20170502-161923.zip
    
    To use the exported libraries in CMake projects use:
    
    "-DCMAKE_TOOLCHAIN_FILE=[...]/scripts/buildsystems/vcpkg.cmake"
    
    Creating 7zip archive...
    Creating 7zip archive... done
    7zip archive exported at: E:/workspace/vcpkg/vcpkg-export-20170502-161923.7z
    
    To use the exported libraries in CMake projects use:
    
    "-DCMAKE_TOOLCHAIN_FILE=[...]/scripts/buildsystems/vcpkg.cmake"
    iii. Exporting multiple libraries for multiple architectures

    You can export multiple libraries as well as multiple architectures of the same library in the same export file.

    > vcpkg export gtest zlib gtest:x64-windows zlib:x64-windows --nuget
    The following packages are already built and will be exported:
    gtest:x86-windows
    gtest:x64-windows
    zlib:x86-windows
    zlib:x64-windows
    Exporting package zlib:x86-windows...
    Exporting package zlib:x86-windows... done
    Exporting package zlib:x64-windows...
    Exporting package zlib:x64-windows... done
    Exporting package gtest:x86-windows...
    Exporting package gtest:x86-windows... done
    Exporting package gtest:x64-windows...
    Exporting package gtest:x64-windows... done
    Creating nuget package...
    Creating nuget package... done
    NuGet package exported at: E:/workspace/vcpkg/vcpkg-export-20170502-150917.nupkg
    
    With a project open, go to Tools->NuGet Package Manager->Package Manager Console and paste:
    
    Install-Package vcpkg-export-20170502-150917 -Source "E:\workspace\vcpkg"

    Using the exported binaries

    i. Visual Studio Project

    To consume the binaries you created using vcpkg export command into a Visual Studio project is to use the vcpkg export –nuget option, and then add the .nupkg to your project as every other NuGet package. Other export options (–zip, –7zip, –raw) contain the necessary .targets file, for msbuild integration in more advanced scenarios, inside scripts\buildsystems\msbuild\.

    ii. CMake

    A CMake toolchain file is included when exporting from vcpkg export. It is in scripts\buildsystems\. To use it, you need to specify the CMAKE_TOOLCHAIN_FILE variable when calling CMake:

    > cmake .. "-DCMAKE_TOOLCHAIN_FILE=E:/workspace/vcpkg/vcpkg-export-20170502-161923/scripts/buildsystems/vcpkg.cmake"

    Tell us what you think

    As always, we really want this project to be your tool. If you need other export formats, just let us know by creating an issue on GitHub or contributing to the code itself!

    We have also verified that all the libraries in the vcpkg catalog work with VS 2017, so if you encounter issues when upgrading, do let us know! We hope you enjoy using vcpkg to migrate your project to Visual Studio 2017.pre>

    Why am I getting these _SCL_SECURE_NO_WARNINGS messages?

    $
    0
    0

    Recently, a C++ developer asked why they were getting diagnostic messages for this code:

    void example(char const * const src, char * const dest) {
        std::copy(src, src + 42, dest);
    }
    

    If you compile this file in debug mode, you’ll get a message like the following:

    xutility(2350,1): warning C4996: 'std::copy::_Unchecked_iterators::_Deprecate': Call to 'std::copy' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' _DEPRECATE_UNCHECKED(copy, _Dest); ^ xutility(2350): note: see declaration of 'std::copy::_Unchecked_iterators::_Deprecate' _DEPRECATE_UNCHECKED(copy, _Dest); .\test.cpp(4): note: see reference to function template instantiation '_OutIt std::copy<const char,char*>(_InIt,_InIt,_OutIt)> ' being compiled with [ _OutIt=char *, _InIt=const char * ] std::copy(src, src + 42, dest);

    This is caused by the STL’s iterator debugging support. If you turn on debugging (with /MTd or /MDd), you’re asking the STL to check the size of the resulting range for you, and if you just give us a plain pointer, there’s no way for std::copy to tell where the end of the range is.

    You can tell the STL where the end of the range is in a number of ways:

    1. If possible, you can pass std::copy a plain array. If you start with an array, we will see what the extent of the array is, and do appropriate bounds checking.

      // copy can now tell that dest is 1234 elements
      void example(char const * const src) {
         char dest[1234]; std::copy(src, src + 42, dest);
      }
    2. Several standard library algorithms received “dual range” versions in C++14. If you use the dual range versions, the second range already provides the necessary bounds checking:

      bool example(char const * const left, const size_t leftSize, char const * const right, const size_t rightSize) {
         // triggers warning
         return equal(left, left + leftSize, right);
         // OK
         return equal(left, left + leftSize, right, right + rightSize);
      } 
    3. You can back the destination with a standard container, such as string or vector. If _ITERATOR_DEBUG_LEVEL is not zero, the iterator has enough information to know where it ends and provide appropriate bounds checking.
    4. You can use stdext::make_checked_array_iterator to create an iterator that knows the destination size.
    5. You can decide to accept the risk of exploitable bugs in your code in this area, and define _SCL_SECURE_NO_WARINGS in your project, or before including any STL headers. With this setting, the STL will bounds check where it can, but will not warn you when it is unable to do so.

    Have a question you want us to write up? Other feedback about this post or content you want to see (like a C++ tutorial on a specific scenario)? Leave it as a comment or email Eric (ebattali@microsoft.com). Thanks!


    Using C++ Modules in Visual Studio 2017

    $
    0
    0

    This post was written by Gabriel Dos Reis, Andrew Pardoe, and Billy O’Neal 

    What Is New?

    The Visual C++ Team is elated to announce that with Visual Studio 2017, it has substantially improved the quality of the C++ Modules TS implementation in Visual Studio, in addition to introducing ability to consume the C++ Standard Library via module interfaces.  These module interfaces for the Standard Library, just like the compiler support for modules, are experimental and will evolve to track the standardization process.

    Getting Started

    Standard Library Modules support is included in Visual Studio 2017 RTM or newer. This capability is currently optional and off by default. In future versions, they will be installed by default alongside the Standard Library headers. Just choose this option when installing or updating your C++ support.

    Install Standard Library Modules

    If you’ve already installed VS 2017 and didn’t install the Standard Library Modules, it’s easy to fix. Just rerun the installer to modify your installation options.

    Rerun VS Installer

    Testing Your Installation

    To verify that you have VS 2017 set up to take advantage of Standard Library Modules, compile and run this simple program (say in a file test-vs2017-slm.cxx) from a Developer Command Prompt. As the feature is still experimental, there is very little built-in support in the VS IDE for modules at this point.

    import std.core; 
     
    int main() { 
        using namespace std; 
        vector<string> v { "Plato", "Descartes", "Bacon" }; 
        copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n")); 
    } 
    

    with the command 

    cl /experimental:module /EHsc /MD /std:c++latest test-vs2017-slm.cxx 
    

    That should effortlessly produce an executable (test-vs2017-slm.exe) that, when executed, prints Plato, Descartes, and Bacon, each on a new line.

    Compiler Switch for Consuming Standard Library Modules

    You need to add the compiler switch /MD when compiling a source file that consumes the standard library modules. The /MD switch brings in the dynamic library for the CRT. In a debug build, you need to use /MDd instead of /MD.

    If you forget to specify /MD (or /MDd for debug builds), you will get warnings from the linker and eventually a linker error LNK2019 indicating unresolved external symbols.

    No other option is needed to take advantage of the Standard Library Modules support. The Standard Library modules are provided only for use with the DLL import libraries of the UCRT.

    Consuming Standard Library Modules from the VS IDE

    If you want to use the IDE instead of the command line, you can configure your project to use experimental modules according to the following steps.

    1. First, open Properties for the project you want to use:

      Open Project Properties

    2. Next, under Configuration Properties -> C/C++ -> Code Generation, verify that Multithreaded Debug DLL or Multithreaded DLL (for Debug and Release, respectively) are set. These are the default options for new projects, so if you have not changed these settings everything should work.

      Use dynamic libraries

    3. Next, make sure C++17 features are enabled under Configuration Properties -> C/C++ -> Language, by selecting C++17 or C++ Latest Draft Standard for any configurations you want to use.

      Use latest draft standard

    4. Lastly, add /experimental:module /module:stdIfcDir "$(VCToolsInstallDir_150)ifc\$(PlatformTarget)" to Configuration Properties -> C/C++ -> Command Line to turn on modules for that project. Note that this step won’t be necessary in future versions of VS 2017: the VS IDE will provide the location of the standard library modules files (the /module:stdIfcDir parameter) for you when you choose to enable C++ Modules.

      Modules configuration properties

    Now build and test run should succeed, showing you the names of three philosophers.

    Running modules test

    Module Exportation Syntax Change

    At the November 2016 C++ standards meeting, the C++ standards committee changed the syntax for exporting a module (see Module Issue #1) from

    export module Bank;

    to 

    export import Bank;

    This release of Visual C++ implements that resolution, in addition to allowing the old syntax with a warning. The C++ committee is considering repurposing the old syntax, with an incompatible meaning.  We encourage you to convert to the new syntax; support for the old syntax will be discontinued to implement the Module TS draft as amended by the ISO C++ standards committee.

    Standard Library Modules (Experimental)

    A key novelty in VS2017 RTM release is support for consuming the C++ Standard Library via modules.  This is an experimental feature and described in the C++ proposal Standard Library Modules. In this release, the modules are organized as follows:

    • std.regex provides the content of header <regex> 
    • std.filesystem provides the content of header <experimental/filesystem> 
    • std.memory provides the content of header <memory> 
    • std.threading provodes the contents of headers <atomic>, <condition_variable>, <future>, <mutex>, <shared_mutex>, <thread> 
    • std.core provides everything else in the C++ Standard Library

    To use any of these modules in your program, just write import M; at toplevel in your source file, where M is any of the modules listed above. See the test example.

    If you want to use modules for header other than the standard library headers, the standard library modules are produced using the /module:export switch described in the initial C++ modules blog post; with /module:export. If you have other libraries on which you depend and want to try a completely header-free experience, you can package those other headers in the same way.

    Future releases will more closely track the Standard Library Modules proposal.

    Call to Action

    Download Visual Studio 2017 today and try out modules in your C++ projects and programs.  You can start with just replacing all #includes of standard headers for containers and algorithms with a simple import std.core; in your source files and adding the compiler switches /experimental:module and /MD or /MDd (if you’re building as debug) to your build definition.  Let us know about your experience.

    In Closing

    As always, we welcome your feedback. Feel free to send any comments through e-mail at visualcpp@microsoft.com, through Twitter @visualc, or Facebook at Microsoft Visual Cpp.

    If you encounter other problems with MSVC in VS 2017 please let us know via the Report a Problem option, either from the installer or the Visual Studio IDE itself. For suggestions, let us know through UserVoice. Thank you!

    C++ at Microsoft Build 2017

    $
    0
    0

    The C++ team is at Build this week. Here are some of the highlights for C++ developers (and since there is a live stream and videos, you do not have to miss everything):

    We hope to see you there.

    CMake support in Visual Studio – what’s new in 2017 15.3 update

    $
    0
    0

    We are excited to announce a the first preview release of Visual Studio 2017 15.3 update in conjunction with our Build 2017 conference!  This preview includes two new features of interest to developers utilizing CMake.  Support for the CMake Ninja generator and CMake CTest integration in the IDE.

    Please download the preview and try out the latest CMake features.  If you are just getting started with CMake, follow the link to learn more about CMake support in Visual Studio.  We are looking forward to your feedback.

    Build with Ninja

    You asked for support for more CMake build generators and we listened.  The latest preview of the CMake tools for Visual Studio now support the Ninja build system.  Keep in mind, this is a preview so there are a few limitations.  The CMake tools for Visual Studio currently only support building for x86 and are not compatible with CTest.  In addition, Ninja builds are currently only supported on 64-bit OSes.  Don’t worry though, these limitations will be resolved by the time 15.3 hits the public channel.

    To get started with the Ninja generator, you will need to edit your CMakeSettings.json file.  Right click on your CMakeLists.txt file and select “Change CMake Settings” to navigate to or create this file if you don’t already have one in your folder:

    Edit CMake Settings

    If you haven’t added a CMakeSettings.json file to your folder yet, you will see something like this:

    CMake Settings JSON

    You can choose the Ninja generator by setting the “generator” tag of each configuration you want to build using Ninja.  If you have an existing CMakeSettings.json file you will need to update the generator from “Visual Studio 15 2017” to “Ninja”.  Keep in mind, there isn’t support yet for x64 configurations.

    The Ninja generator is selected by default for x86 builds in the preview releases of 15.3, but this will be changing once it is released to the public channel.

    CTest Integration

    New generators are great, but it is also important for developers to be assured of the quality of their code.  The preferred way to do this with CMake projects is to use CTest.  The good news, if you are already using CTest, you don’t need to do anything.  The latest preview of Visual Studio should detect the tests without any intervention on your part.

    CTest Run Tests

    If you don’t see the “Run Tests” menu item, make sure you are using the Visual Studio CMake generator in your CMakeSettings.json file.  This limitation will be resolved in a future release.

    Once you select “Run Tests” from the CMake menu or by right clicking on your CMakeLists.txt file, your project will be automatically built, and your tests will run. The output is streamed to the CMake Output window – CTest is not yet integrated with the Test Explorer.

    Send us Feedback

    To try out the latest and greatest CMake features and give us some early feedback, please download and install the latest Visual Studio 2017 Preview.  As always, we welcome your feedback.  Feel free to send any comments through e-mail at cmake@microsoft.com, through Twitter @visualc, or Facebook at Microsoft Visual Cpp.

    If you encounter other problems with Visual Studio 2017 please let us know via Report a Problem, which is available in both the installer and the IDE itself.  For suggestions, let us know through UserVoice. We look forward to your feedback!

    C++17 Features In Visual Studio 2017 Version 15.3 Preview

    $
    0
    0

    Visual Studio 2017 version 15.3 preview is now available, containing an updated Visual C++ toolset (i.e. compiler, linker, and libraries). Like VS 2015’s Updates, we’re adding C++17 features in VS 2017’s Updates, at a similar release frequency. Unlike VS 2015’s Updates (which combined IDE and toolset changes), VS 2017’s IDE is being updated more frequently (with what we’re calling “minor Updates”). That’s why this is the first toolset Update (also called a “foundational Update”).

    Here’s the compiler feature table, with some notes. While you can download VS 2017 15.3 preview 1 today, we’ve checked in additional features for Preview 2 which will be released soon. We want to tell you about both sets of features, so features that will be available in Preview 2 (but aren’t available today) are marked as [P2].

    C++03/11 Core Language Features

    Status

    Paper

    Notes

    [Everything else]

    VS 2015

    [A]

    Two-phase name lookup

    Partial

    [twoPhase]

    Expression SFINAE

    Partial

    N2634

    [B]

    C99 preprocessor

    Partial

    N1653

    [C]

    Extended integer types

    N/A

    N1988

    [D]

    C++14 Core Language Features

    Status

    Paper

    Notes

    Avoiding/fusing allocations

    N/A

    N3664

    [E]

    Tweaked wording for contextual conversions

    VS 2013

    N3323

    Binary literals

    VS 2015

    N3472

    auto and decltype(auto) return types

    VS 2015

    N3638

    init-captures

    VS 2015

    N3648

    Generic lambdas

    VS 2015

    N3649

    Variable templates

    VS 2015.2

    N3651

    Extended constexpr

    VS 2017

    N3652

    NSDMIs for aggregates

    VS 2017

    N3653

    [[deprecated]] attribute

    VS 2015

    N3760

    Sized deallocation

    VS 2015

    N3778

    Digit separators

    VS 2015

    N3781

    C++17 Core Language Features

    Status

    Paper

    Notes

    New rules for auto with braced-init-lists

    VS 2015

    N3922

    [14]

    Terse static_assert

    VS 2017

    N3928

    typename in template template-parameters

    VS 2015

    N4051

    [14]

    Removing trigraphs

    VS 2010

    N4086

    [14]

    Nested namespace definitions

    VS 2015.3

    N4230

    Fixing qualification conversions

    No

    N4261

    Attributes for namespaces and enumerators

    VS 2015

    N4266

    [14]

    u8 character literals

    VS 2015

    N4267

    [14]

    Allowing more non-type template args

    No

    N4268

    Fold expressions

    No

    N4295

    Removing some empty unary folds

    No

    P0036R0

    Removing the register keyword

    VS 2017.3

    P0001R1

    Removing operator++ for bool

    VS 2017.3

    P0002R1

    Adding noexcept to the type system

    No

    P0012R1

    Extended aggregate initialization

    No

    P0017R1

    Capturing *this by value

    VS 2017.3

    P0018R3

    __has_include

    VS 2017.3 [P2]

    P0061R1

    [14]

    Rewording inheriting constructors

    No

    P0136R1

    Direct-list-init of fixed enums from integers

    VS 2017.3

    P0138R2

    constexpr lambdas

    VS 2017.3

    P0170R1

    Generalized range-based for-loops

    VS 2017

    P0184R0

    [14]

    [[fallthrough]] attribute

    VS 2017

    P0188R1

    [[nodiscard]] attribute

    VS 2017.3

    P0189R1

    [[maybe_unused]] attribute

    VS 2017.3

    P0212R1

    Hexfloat literals

    No

    P0245R1

    Using attribute namespaces without repetition

    VS 2017.3

    P0028R4

    Over-aligned dynamic memory allocation

    No

    P0035R4

    Template argument deduction for class templates

    No

    P0091R3

    Declaring non-type template parameters with auto

    No

    P0127R2

    Guaranteed copy elision

    VS 2017.3

    P0135R1

    Refining expression evaluation order

    No

    P0145R3

    Structured bindings

    VS 2017.3

    P0217R3

    Ignoring unrecognized attributes

    No

    P0283R2

    constexpr if-statements

    VS 2017.3 [P2]

    P0292R2

    [F]

    Selection statements with initializers

    VS 2017.3 [P2]

    P0305R1

    Inline variables

    No

    P0386R2

    Matching template template-parameters to compatible arguments

    No

    P0522R0

    Removing dynamic-exception-specifications

    No

    P0003R5

    Pack expansions in using-declarations

    No

    P0195R2

    [A] Except for dynamic exception specifications, which were deprecated in C++11 and mostly removed in C++17. Note that C++17 18.4 [except.spec]/2 says “The noexcept-specifier throw() is deprecated (D.3), and equivalent to the noexcept-specifier noexcept(true).” but VS 2017 version 15.3 preview currently considers throw() to be equivalent to __declspec(nothrow).

    [twoPhase] While two-phase name lookup isn’t supported in VS 2017 version 15.3 preview, the compiler team is performing major work behind the scenes. For Preview 2, the /permissive- compiler option will activate partial support for two-phase name lookup (partial meaning roughly 60% complete). We’ll publish a detailed blog post in the future. (edited on May 10 at 3:30 PM Pacific Time for accuracy)

    [B] Although Expression SFINAE is partially supported, it’s nearly complete. It was sufficient for the STL back in VS 2015.2, and Expression SFINAE has received further bugfixes for additional libraries like Boost. The most significant remaining deficiency is the need to use unique tag types when performing void_t/decltype Expression SFINAE.

    [C] C99 preprocessor support is still partial, in that variadic macros mostly work. We’re planning to overhaul the preprocessor before marking this as complete.

    [D] Extended integer types are permitted but not required. Like Clang and GCC, we’ve chosen not to implement any.

    [E] Avoiding/fusing allocations is permitted but not required. For the time being, we’ve chosen not to implement this.

    [F] Supported under /std:c++14 with “warning C4984: ‘if constexpr’ is a C++17 language extension”. This will allow the STL (in the future) to use “if constexpr” within its implementation.

    [14] These features are always enabled, even under /std:c++14.

    [P2] These features have been checked in and will be available in VS 2017.3 Preview 2.

    Here’s the STL feature table:

    Status

    Std

    Paper

    Title

    Notes

    missing

    C++17

    P0604R0

    Changing is_callable/result_of To is_invocable/invoke_result (Options A and B)
    missing

    C++17

    P0005R4

    not_fn()
    patch

    C++17

    P0358R1

    Fixes For not_fn()
    missing

    C++17

    P0618R0

    Deprecating <codecvt>
    missing

    C++17

    P0521R0

    Deprecating shared_ptr::unique()
    missing

    C++17

    P0174R2

    Deprecating Vestigial Library Parts
    missing

    C++17

    P0003R5

    Removing Dynamic Exception Specifications
    missing

    C++17

    P0302R1

    Removing Allocator Support In std::function
    missing

    C++17

    P0433R2

    Deduction Guides For The STL
    missing

    C++17

    P0607R0

    Inline Variables For The STL (Options A and B2)
    missing

    C++17

    P0258R2

    has_unique_object_representations
    missing

    C++17

    P0426R1

    constexpr For char_traits
    missing

    C++17

    P0063R3

    C11 Standard Library
    missing

    C++17

    P0033R1

    Rewording enable_shared_from_this
    missing

    C++17

    P0414R2

    shared_ptr<T[]>, shared_ptr<T[N]>
    patch

    C++17

    P0497R0

    Fixing shared_ptr For Arrays
    missing

    C++17

    P0083R3

    Splicing Maps And Sets
    patch

    C++17

    P0508R0

    Clarifying insert_return_type
    missing

    C++17

    P0067R5

    Elementary String Conversions

    C++17

    P0220R1

    Library Fundamentals V1
    missing

    C++17

    <memory_resource>
    patch

    C++17

    P0337R0

    Deleting polymorphic_allocator Assignment
    missing

    C++17

    P0030R1

    hypot(x, y, z)
    missing

    C++17

    P0226R1

    Mathematical Special Functions
    missing

    C++17

    P0024R2

    Parallel Algorithms

    [G]

    patch

    C++17

    P0336R1

    Renaming Parallel Execution Policies
    patch

    C++17

    P0394R4

    Parallel Algorithms Should terminate() For Exceptions
    patch

    C++17

    P0452R1

    Unifying <numeric> Parallel Algorithms
    missing

    C++17

    P0218R1

    <filesystem>
    patch

    C++17

    P0219R1

    Relative Paths For Filesystem
    patch

    C++17

    P0317R1

    Directory Entry Caching For Filesystem
    patch

    C++17

    P0392R0

    Supporting string_view In Filesystem Paths
    patch

    C++17

    P0430R2

    Supporting Non-POSIX Filesystems
    patch

    C++17

    P0492R2

    Resolving NB Comments For Filesystem
    VS 2017.3 [P2]

    C++17

    P0031R0

    constexpr For <array> (Again) And <iterator>
    VS 2017.3 [P2]

    C++17

    P0084R2

    Emplace Return Type
    VS 2017.3 [P2]

    C++17

    P0295R0

    gcd(), lcm()
    VS 2017.3 [P2]

    C++17

    P0298R3

    std::byte

    [H]

    VS 2017.3 [P2]

    C++17

    P0435R1

    Overhauling common_type

    [14]

    VS 2017.3 [P2]

    C++17

    P0505R0

    constexpr For <chrono> (Again)
    VS 2017.3 [P2]

    C++17

    P0548R1

    Tweaking common_type And duration

    [14]

    VS 2017.3

    C++17

    Boyer-Moore search()
    VS 2017.3

    C++17

    P0040R3

    Extending Memory Management Tools
    VS 2017.3

    C++17

    P0152R1

    atomic::is_always_lock_free
    VS 2017.3

    C++17

    P0154R1

    hardware_destructive_interference_size, etc.
    VS 2017.3

    C++17

    P0156R2

    Renaming Variadic lock_guard To scoped_lock
    VS 2017.3

    C++17

    P0253R1

    Fixing Searcher Return Types
    VS 2017.3

    C++17

    P0403R1

    UDLs For <string_view> (“meow”sv, etc.)
    VS 2017.3

    C++17

    P0418R2

    atomic compare_exchange memory_order Requirements

    [14]

    VS 2017.3

    C++17

    P0513R0

    Poisoning hash

    [14]

    VS 2017.3

    C++17

    P0516R0

    Marking shared_future Copying As noexcept

    [14]

    VS 2017.3

    C++17

    P0517R0

    Constructing future_error From future_errc

    [14]

    VS 2017.3

    C++17

    P0558R1

    Resolving atomic<T> Named Base Class Inconsistencies

    [I] [14]

    VS 2017.3

    C++17

    P0599R1

    noexcept hash

    [14]

    VS 2017

    C++17

    <algorithm> sample()
    VS 2017

    C++17

    <any>
    VS 2017

    C++17

    <optional>
    VS 2017

    C++17

    <string_view>
    VS 2017

    C++17

    <tuple> apply()
    VS 2017

    C++17

    P0032R3

    Homogeneous Interface For variant/any/optional
    VS 2017

    C++17

    P0077R2

    is_callable, is_nothrow_callable
    VS 2017

    C++17

    P0088R3

    <variant>
    VS 2017

    C++17

    P0163R0

    shared_ptr::weak_type
    VS 2017

    C++17

    P0209R2

    make_from_tuple()
    VS 2017

    C++17

    P0254R2

    Integrating string_view And std::string
    VS 2017

    C++17

    P0307R2

    Making Optional Greater Equal Again
    VS 2017

    C++17

    P0393R3

    Making Variant Greater Equal
    VS 2017

    C++17

    P0504R0

    Revisiting in_place_t/in_place_type_t<T>/in_place_index_t<I>
    VS 2017

    C++17

    P0510R0

    Rejecting variants Of Nothing, Arrays, References, And Incomplete Types
    VS 2015.3

    C++17

    P0025R1

    clamp()
    VS 2015.3

    C++17

    P0185R1

    is_swappable, is_nothrow_swappable
    VS 2015.3

    C++17

    P0272R1

    Non-const basic_string::data()
    VS 2015.2

    C++17

    N4387

    Improving pair And tuple

    [14]

    VS 2015.2

    C++17

    N4508

    shared_mutex (Untimed)

    [14]

    VS 2015.2

    C++17

    P0004R1

    Removing Deprecated Iostreams Aliases

    [J]

    VS 2015.2

    C++17

    P0006R0

    Variable Templates For Type Traits (is_same_v, etc.)

    [14]

    VS 2015.2

    C++17

    P0007R1

    as_const()

    [14]

    VS 2015.2

    C++17

    P0013R1

    Logical Operator Type Traits (conjunction, etc.)

    [14]

    VS 2015.2

    C++17

    P0074R0

    owner_less<>

    [14]

    VS 2015.2

    C++17

    P0092R1

    <chrono> floor(), ceil(), round(), abs()

    [14]

    VS 2015.2

    C++17

    P0156R0

    Variadic lock_guard

    [14]

    VS 2015

    C++17

    N3911

    void_t

    [14]

    VS 2015

    C++17

    N4089

    Safe Conversions In unique_ptr<T[]>

    [14]

    VS 2015

    C++17

    N4169

    invoke()

    [14]

    VS 2015

    C++17

    N4190

    Removing auto_ptr, random_shuffle(), And Old <functional> Stuff

    [K]

    VS 2015

    C++17

    N4258

    noexcept Cleanups

    [14]

    VS 2015

    C++17

    N4259

    uncaught_exceptions()

    [14]

    VS 2015

    C++17

    N4277

    Trivially Copyable reference_wrapper

    [14]

    VS 2015

    C++17

    N4279

    insert_or_assign()/try_emplace() For map/unordered_map

    [14]

    VS 2015

    C++17

    N4280

    size(), empty(), data()

    [14]

    VS 2015

    C++17

    N4366

    Precisely Constraining unique_ptr Assignment

    [14]

    VS 2015

    C++17

    N4389

    bool_constant

    [14]

    VS 2013

    C++17

    N4510

    Supporting Incomplete Types In vector/list/forward_list

    [14]

    N/A

    C++17

    N4284

    Contiguous Iterators
    N/A

    C++17

    P0175R1

    Synopses For The C Library
    N/A

    C++17

    P0180R2

    Reserving Namespaces For Future Standardization
    N/A

    C++17

    P0346R1

    A <random> Nomenclature Tweak
    N/A

    C++17

    P0371R1

    Discouraging memory_order_consume
    N/A

    C++17

    P0467R2

    Requiring Forward Iterators In Parallel Algorithms
    N/A

    C++17

    P0502R0

    Parallel Algorithms Should terminate() For Exceptions, Usually
    N/A

    C++17

    P0503R0

    Correcting Library Usage Of “literal type”
    N/A

    C++17

    P0509R1

    Updating “Restrictions on exception handling”
    N/A

    C++17

    P0518R1

    Copying Trivially Copy Constructible Elements In Parallel Algorithms
    N/A

    C++17

    P0523R1

    Relaxing Complexity Requirements Of Parallel Algorithms (General)
    N/A

    C++17

    P0574R1

    Relaxing Complexity Requirements Of Parallel Algorithms (Specific)
    N/A

    C++17

    P0623R0

    Final C++17 Parallel Algorithms Fixes

    The “missing” and “patch” papers have been grouped together and should be self-explanatory. The Library Fundamentals V1 paper has been decomposed into individual features marked by “…”. Finally, “N/A” indicates papers that didn’t change normative wording, or that didn’t really result in new features for users. For example, when we implement Parallel Algorithms, we’ll implement the current Standardese. For tracking purposes, P0394R4 (Parallel Algorithms Should terminate() For Exceptions) is important for users and implementers to be aware of, while P0502R0 (Parallel Algorithms Should terminate() For Exceptions, Usually) isn’t (it permits non-Standard execution policies to have different behavior).

    [G] Serial for_each_n() will be available in Preview 2.

    [H] /std:c++17 and /std:c++latest enable std::byte. It can be disabled by defining _HAS_STD_BYTE to 0.

    [I] We’ve implemented the user-visible parts of P0558R1 (Resolving atomic<T> Named Base Class Inconsistencies), except for the signatures of atomic_meow() and atomic_meow_explicit(), which can be observed by taking their addresses or providing explicit template arguments.

    [J] /std:c++17 and /std:c++latest remove the old iostreams members. They can be restored by defining _HAS_OLD_IOSTREAMS_MEMBERS to 1.

    [K] /std:c++17 and /std:c++latest remove auto_ptr, random_shuffle(), and the old <functional> stuff. They can be restored by defining _HAS_AUTO_PTR_ETC to 1.

    We’ve also implemented 29 LWG issue resolutions, fixed several bugs, and made many behind-the-scenes improvements, which we’ll be writing about as we get closer to VS 2017.3’s final release.

    Please try out Visual Studio 2017 version 15.3 preview and let us know what you think. (Remember that you must compile with either /std:c++17 or /std:c++latest to enable C++17 features, aside from those marked [14] above – and remember that [P2] features won’t be available until Preview 2.) You can use the IDE’s Report A Problem to report bugs. For compiler and library bugs, it’s important to provide self-contained test cases.

    Linux C++ improvements for cross-platform code sharing and type visualization

    $
    0
    0

    In Visual Studio 2017 we introduced the Linux development with C++ workload. This tutorial is going to walk through some of the improvements we have made in the 15.2 release using the classic spinning cube demo from Julien Guertault’s OpenGL tutorial. We have shown how to use this OpenGL demo in our Linux workload before. What we are showing here is how to use this as a single source base for both Windows and Linux using Shared Items in Visual Studio. From there we will show off some improvements we have made to debugger type visualization for Linux C++, for both natvis and Python pretty printing.

    C++ cross-platform code sharing with shared items

    Shared Items Projects were introduced in Visual Studio 2015 Update 1 to share cross platform C and C++ code between projects that targeted specific platforms. We introduced them by showing how Shared Items can be used for common code across Android, iOS and Universal Windows Platform. We now also have support for Shared Items with our Linux C/C++ projects.

    To try this out you will need to have at minimum Visual Studio 2017 15.2 installed with the Desktop C++ and Linux development with C++ workloads installed. For the Linux portion you will need a Linux machine that has the following libraries installed.

    sudo apt-get install libgles1-mesa libgles1-mesa-dev freeglut3 freeglut3-dev

    You will want to copy your include files locally to your Windows box for enabling IntelliSense as well (after adding those libraries).

    To get started create a new solution and choose Shared Items Project under Visual C++ -> General, name the Solution and Project CrossPlatCube.  Get the source for Spinning Cube from Julien Guertault’s OpenGL tutorial. Extract it and add main.c to your project as main.cpp. Now add a new project to your solution and choose Visual C++ -> Empty Project and name it WindowsCube. Now right click on References and choose add reference. In the dialog choose Shared Projects and select CrossPlatCube. We’re not going to add any source to this project, we’re just using it to build the source in the Shared Items project. To do so get the prebuilt OpenGL libraries from Martin Payne’s site. Extract these on your machine and in the project properties of the WindowsCube project add references to the include and library directories under VC++ Directories to enable IntelliSense. You will also need to provide the include directory location in the project properties under General -> Additional Include Directories and the location of freeglut.lib under Linker -> Additional Dependencies. You should now be able to build and run the WindowsCube project and see the spinning cube.

    Now add a new Empty Project (Linux) to the solution from Add -> New Project -> Visual C++ -> Cross Platform -> Linux and name it LinuxCube. Add a reference to the CrossPlatCube project as you did for the empty Windows project. Before moving on open main.cpp from the CrossPlatCube project if it is not currently open. Note under the file name tab there is a context menu, if you drop this down and select the WindowsCube project you will see that there are purple squiggles for many items because we have not added the include location for the Linux project yet. The purple indicates these are not syntax errors with the current platform project context, but are errors in another context the shared items code is used in. If you switch the context to the LinuxCube project the squiggles will be red indicating they are errors in this context.

    linuxsharing

    Now open your Project Properties make sure under General you have the correct remote machine selected and add your local folder with your Linux include files under VC++ Directories -> Include Directories. On the Debugging Property Page add export DISPLAY=:0.0 to the Pre-Launch command. Under the Linker Input Property Page add the library dependencies: m;GL;GLU;glut. Now right click the Linux project and set it as the startup project. You should now be able to build and run it on your Linux machine using the same code that you built your Windows app from.

    You’ve already seen some basic IntelliSense, build and launch/debug capabilities in the above example using Shared Items across platforms. Shared Items also give you platform specific Semantic colorization, Quick Info, Parameter Help and Member List results that are specific to that selected project’s platform. That’s not all though, browsing and refactoring support functionality like Go to/Peek definition/declaration, Find all References, Call Hierarchy and Class View are all also available for any platforms you project targets. You’ll be able to easily navigate deeply into platform specific headers and back to your shared source.  You can read more about these capabilities in this shared items post.

    Debugger types visualization improvements

    Another area we have improved in Visual Studio 15.2 is debugger types visualizations for Linux C/C++. This has been done using both Visual Studios natvis format that provides visualizations of C/C++ types and supporting Python pretty printing in GDB. We’ll talk about nativs first. To get something interesting to look at lets add some usage of libstdc++ types to the cube example.

    Add these includes and arrary to main.cpp in the CrossPlatCube project.

    #include <vector>
    #include <array>
    
    std::vector<std::array<GLfloat, 6>> vertices = {
        { 0, 0, 0, -1, -1, -1},
        { 0, 0, 1, -1, -1, 1},
        { 0, 1, 1, -1,  1,  1 },
        { 0, 1, 0, -1,  1, -1 },
        { 1, 0, 0, 1, -1, -1 },
        { 1, 0, 1, 1, -1,  1 },
        { 1, 1, 1, 1,  1,  1 },
        { 1, 1, 0, 1,  1, -1 },
        { 0, 0, 0, -1, -1, -1 },
        { 0, 0, 1, -1, -1,  1 },
        { 1, 0, 1, 1, -1,  1 },
        { 1, 0, 0, 1, -1, -1 },
        { 0, 1, 0, -1,  1, -1 },
        { 0, 1, 1, -1,  1,  1 },
        { 1, 1, 1, 1,  1,  1 },
        { 1, 1, 0, 1,  1, -1 },
        { 0, 0, 0, -1, -1, -1 },
        { 0, 1, 0, -1,  1, -1 },
        { 1, 1, 0, 1,  1, -1 },
        { 1, 0, 0, 1, -1, -1 },
        { 0, 0, 1, -1, -1,  1 },
        { 0, 1, 1, -1,  1,  1 },
        { 1, 1, 1, 1,  1,  1 },
        { 1, 0, 1, 1, -1,  1 },
    };

    Now at what was line 45 where this comment is remove the calls to glCoror3f and glVertex3f and replace them with a for loop over the array as so.

        /* Every four calls to glVertex, a quad is drawn */
        for (auto vertex : vertices)
        {
            glColor3f(vertex[0], vertex[1], vertex[2]);
            glVertex3f(vertex[3], vertex[4], vertex[5]);
        }

    Set a break point in the for loop and run the application on Linux. If you are on Visual Studio 2017 15.1 or earlier if you were to expand the for range it would look something like this.

    typebefore

    That’s quite deep before you get to your data. In Visual Studio 2017 15.2 it now looks like this.

    typesnatvis

    Much easier to get to your data and the actual type information you care about.

    We are providing a natvis visualizer for libstdc++ that will work with both the default gdbserver and gdb modes of Linux projects in Visual Studio 2017. This post describes how to build your own visualizers using natvis here, once created just add the file to your project root and it will be picked up and used. You can also still get to the raw view as opposed to the visualized view if you need it.

    We’ve also added support for Python pretty printers using gdb mode. You can learn more about Python pretty printing from the GNU site, but basically this is the way that visualizations for types are enabled in GDB. It was introduced in GDB 7.0 and printers have shipped with GCC since version 4.5 for libstdc++. If you are using something older you may need to take additional steps to enable them. Other libraries on Linux may or may not provide printers, but similarly to natvis you can write your own. Let’s look at the same example as above.

    typespythonprinter

    Here you can see what was the raw view is now neatly visualized using what came back from the built in Python pretty printer on Linux. Here I have expanded to the same element in the array as the above examples. At each expansion level you can see the Visualized View that shows the natvis visualization is present, unexpanded here.

    Python pretty printing is on by default. If you experience any performance problems with this (large arrays etc.) it can be deactivated under project properties -> Debugging -> Enable Python Pretty Printing).

    Wrap up

    We hope these improvements make our Linux C/C++ support more useful to you. You can find out more about our Linux C/C++ support here. As always, we love to hear from you, what doesn’t work but also what does and how you are using it. We are continuing to make investments to improve our Linux C/C++ story and can’t wait to show you what we’re working on now.

    — Marc Goodner, @robotdad

    Viewing all 1541 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>