Getting Started with Visual Studio for C and C++ Development
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:
- Setting Up Visual Studio
- Opening Projects or Folders of Code
- Building the Application
- Code Editing & Navigation
- Debugging and Diagnosing Issues
- Working With A Team
- Other Topics
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 development with C++ Provides the tools needed for building and debugging classic desktop applications. This includes classic Win32 console applications.|
|Mobile development with C++ Includes the tools needed for targeting Android and iOS.|
|Game development with C++ Enables you to quickly and easily get started building games using DirectX, Unreal Engine, or Cocos2d.|
|Linux development with C++ All the necessary tools for developing and debugging Linux applications.|
|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.
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).
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: 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. 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.
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.
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.
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.
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.
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”.
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. 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. 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:
- Place a breakpoint on line 14 of the main function.
- Click the green arrow at the top of the IDE or press F5 to begin debugging.
- Find out what the value of testInt is before it is initialized by hovering over the value in the code.
- Look at the value of testInt in the Autos window.
- Press the green arrow or F5 again to stop debugging.
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. 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 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 the C++ Debugging and Diagnostics blog post to learn more.
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. 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:
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. 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. 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.
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. 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.
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.
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 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.
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.
@Augustin : Hi could you update “Attempt to build the application by going to Build > Build Solution (or alternatively by pressing F7). ” to “…….pressing F6” because it is F6 on Visual Studio.
I’m using the latest version (16.2.0) and the Test Explorer example produced no output under the headers with either the valid or invalid Assert calls. In the Output window under the code it says there were no tests found to run. After trying to run it in Test Exporer I notice there is a small icon above TEST_METHOD(TestMethod1) in the code window. Hovering the mouse exposed text which indicated that no tests had been run. Clicking on the icon gave the option to Run or Debug. Clicking Run turned the icon to a red X and the message text changed to say the test had failed. Removing the invalid Assert statement and choosing Run again from the icon changed it to a Green checkmark and the text changed to Test Passed.
Plss pls Tell me how can i run /build a emptt project in Vs 2019 C++ 〒_〒 ๏︿๏
These comments result from using Visual Studio 19 as a beginner.
Instructions given are to download the project then open the solution file.
Opening the solution file via double click initiated ‘Blend for Visual Studio’ which was too disconcerting, so this was abandoned in favour of opening the project solution inside an active Visual Studio session.
Unfortunately, with either open method the solution references files with paths to the ‘project author’ folders, so it cannot be opened simply using these instructions as loading errors occur with these files.
Fortunately Visual Studio 19 has ‘File/New/Project from existing code’ which was a useful workaround.