April 21st, 2017
heart5 reactions

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

Will Buik
Program Manager

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 ofVisual 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, andEnterprise. TheCommunity 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 cancompare 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 whatworkloadsyou want to install, choosing only the components you want, and nothing you don’t. The following workloads are under the C++ umbrella:

Desktop Workload IconDesktop development with C++Provides the tools needed for building and debugging classic desktop applications. This includes classic Win32 console applications.
Mobile Workload IconMobile development with C++Includes the tools needed for targeting Android and iOS.
Game Workload IconGame development with C++Enables you to quickly and easily get started building games using DirectX, Unreal Engine, or Cocos2d.
Linux Workload IconLinux development with C++All the necessary tools for developing and debugging Linux applications.
UWP Workload IconUniversal Windows Platform developmentThis 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 selectingModify.

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

Once you have made your selection and clickedInstall, 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 viaQuick Launch, the search box at the upper right of the IDE (or pressCtrl+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 anOpen 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 abuilt-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 opendemoApplication, double click the.sln file, or from Visual Studio go toFile > 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 theSolution Explorer, pictured below:Solution Explorer WindowNew projects can be also created by going toFile > New > Project… and selecting the template that is appropriate. Console applications are underVisual 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 ofDebugandx86.Project ConfigurationAttempt to build the application by going toBuild > Build Solution (or alternatively by pressingF7). The build will fail, since the code contains an error.TheOutput 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 theError 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 theC++ 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 isIntelliSense, 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 thearrow keys, and complete symbols withTab.

In the main function try adding a call to thefarewellfunction to themySorterobject. You should seeIntelliSensepop up with all the possible functions available from thesorterclass.IntelliSense

Go To

To efficiently write and understand code, easy code navigation is essential. By using theGo 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 theGo Todialog 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 pressingCtrl+G. Try usingGo To to navigate around the demo project.

Use theGo To menu(Ctrl+T) to open the filesorter.h by typing “f sorter.h”.Use theCtrl+Gshortcut to go toline 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 pressingAlt+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. PressEscto close the preview window. You can also go directly to the definition by pressing onlyF12.

UsePeek Definition on theprintVectorfunction by selecting the function and pressingAlt+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 pressCtrl+R, Ctrl+R or right-click it and chooseRename. 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 thebreakpoint, 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.BreakpointWhen 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 online 33 ofdemoApplication.cpp by clicking the bar to the left of the line numbers.

Click the red circle again to remove the breakpoint.Start DebuggingTo begin debugging, you can either press the green arrow at the top of the IDE or pressF5. Once the program has stopped on thebreakpoint, 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 theAutos 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 online 14of themainfunction.
  2. Click the green arrow at the top of the IDE or pressF5 to begin debugging.
  3. Find out what the value oftestIntis before it is initialized by hovering over the value in the code.
  4. Look at the value oftestIntin theAutos window.
  5. Press the green arrow orF5again to stop debugging.

Breakpoint StopAutos WindowWhen you have sufficiently understood the current state of the program, you can press the green arrow button or pressF5again 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.SteppingStep 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 (orShift+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 logical 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 theC++ 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 aNative Unit Test Project to the solution.

Add a test project to the demo. This is done by going toFile > New > Project then selectingVisual C++ > Test > Native Unit Test Project. Make sure to choose theAdd to solution option in the Solution dropdown. You can also simply right-click your solution name in theSolution Explorer and chooseAdd > New Project to accomplish the same task.Create Test ProjectOnce 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 AssertOnce you have added a test, you can run the test by going toTest > Run > All Tests in the menu at the top of the IDE. Once you have run the tests, you will see the results in theTest Explorer window.

Run your test by going toTest > Run > All Tests. Try adding another test that will fail, and running the tests again.Test Explorer WindowIf 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 theC++ 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 usingGitorTeam Foundation Server to manage your codebase. To create a new repo for a project, click theAdd 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 ControlOnce you do that, a local repository will be made for your project. From here you can make commits, or push your changes to a remoteGit service such as GitHub. This is all managed in theTeam Explorer window.Team Explorer Window

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

You can also very easily clone from source control from theTeam Explorer window. ChooseProjects > 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 ProjectClone ProjectTo learn more about working on a project as a team in Visual Studio, check out theVisual 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 itsCode 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 theAnalyzemenu and choosingRun Code Analysis > On Solution. Learn more aboutCode Analysis as well as the C++ Core Guidelines Checkers in theannouncement blog post.

Library Acquisition

Library acquisition in C++ can be challenging. While Visual Studio has support forNuGetpackage management, more recently a new tool calledvcpkgwas launched.Vcpkgis 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 theannouncement 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 ondocs.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 atvisualcpp at microsoft.com and you can provide feedback viaHelp > Report A Problem in the product, or viaDeveloper Community.

Category
Share

Author

Will Buik
Program Manager

Will is a Program manager on Visual Studio's C++ IDE team. He works on the C++ project system and design-time language features such as IntelliSense.

5 comments

Discussion is closed.Login to edit/delete existing comments.

Stay informed

Get notified when new posts are published.
Follow this blog