Jul 08, 2017 dev c debug, dev c debug not working, dev c debug watch variable, dev c debugger, dev c debugger not working.
In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger on Windows.
After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you details about the Microsoft C++ toolset or the C++ language. For those subjects, there are many good resources available on the Web.
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
To successfully complete this tutorial, you must do the following:
- Install Visual Studio Code.
- Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for 'c++' in the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)).
- Install the Microsoft Visual C++ (MSVC) compiler toolset.If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it's not installed, then check the box and click the Modify button in the installer.You can also install just the C++ Build Tools, without a full Visual Studio IDE installation. From the Visual Studio Downloads page, scroll down until you see Tools for Visual Studio under the All downloads section and select the download for Build Tools for Visual Studio.This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check the C++ build tools workload and select Install.
Check your Microsoft Visual C++ installation
To use MSVC from a command line or VS Code, you must run from a Developer Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.
To open the Developer Command Prompt for VS, start typing 'developer' in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Click on the item to open the prompt.
You can test that you have the C++ compiler,
cl.exe
, installed correctly by typing 'cl' and you should see a copyright message with the version and basic usage description.If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn't want to put projects there), navigate to your user folder (
C:users{your username}
) before you start creating new projects.Create Hello World
From the Developer Command Prompt, create an empty folder called 'projects' where you can store all your VS Code projects, then create a subfolder called 'helloworld', navigate into it, and open VS Code (
code
) in that folder (.
) by entering the following commands:C# If Debug Not Working
The 'code .' command opens VS Code in the current working folder, which becomes your 'workspace'. As you go through the tutorial, you will see three files created in a
.vscode
folder in the workspace:tasks.json
(build instructions)launch.json
(debugger settings)c_cpp_properties.json
(compiler path and IntelliSense settings)
Add a source code file
In the File Explorer title bar, select the New File button and name the file
helloworld.cpp
.Add hello world source code
Now paste in this source code:
Now press ⌘S (Windows, Linux Ctrl+S) to save the file. Notice how the file you just added appears in the File Explorer view (⇧⌘E (Windows, Linux Ctrl+Shift+E)) in the side bar of VS Code:
You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.
The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You'll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.
Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the
X
(Clear Notification).Explore IntelliSense
In your new
helloworld.cpp
file, hover over vector
or string
to see type information. After the declaration of the msg
variable, start typing msg.
as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg
object:You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.
Build helloworld.cpp
Next, you will create a
tasks.json
file to tell VS Code how to build (compile) the program. This task will invoke the Microsoft C++ compiler to create an executable file based on the source code.From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose cl.exe build active file, which will build the file that is currently displayed (active) in the editor.
This will create a
tasks.json
file in a .vscode
folder and open it in the editor.Your new
tasks.json
file should look similar to the JSON below:The
command
setting specifies the program to run; in this case that is 'cl.exe'. The args
array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler. This task tells the C++ compiler to take the active file (${file}
), compile it, and create an executable file (/Fe:
switch) in the current directory (${fileDirname}
) with the same name as the active file but with the .exe
extension (${fileBasenameNoExtension}.exe
), resulting in helloworld.exe
for our example.Note: You can learn more about
task.json
variables in the variables reference.The
label
value is what you will see in the tasks list; you can name this whatever you like.The
problemMatcher
value selects the output parser to use for finding errors and warnings in the compiler output. For cl.exe, you'll get the best results if you use the $msCompile
problem matcher.The
'isDefault': true
value in the group
object specifies that this task will be run when you press ⇧⌘B (Windows, Linux Ctrl+Shift+B). This property is for convenience only; if you set it to false, you can still run it from the Terminal menu with Tasks: Run Build Task.Running the build
- Go back to
helloworld.cpp
. Your task builds the active file and you want to buildhelloworld.cpp
. - To run the build task defined in
tasks.json
, press ⇧⌘B (Windows, Linux Ctrl+Shift+B) or from the Terminal main menu choose Tasks: Run Build Task. - When the task starts, you should see the Integrated Terminal panel appear below the source code editor. After the task completes, the terminal shows output from the compiler that indicates whether the build succeeded or failed. For a successful C++ build, the output looks something like this:
- Create a new terminal using the + button and you'll have a new terminal (running PowerShell) with the
helloworld
folder as the working directory. Runls
and you should now see the executablehelloworld.exe
along with various intermediate C++ output and debugging files (helloworld.obj
,helloworld.pdb
). - You can run
helloworld
in the terminal by typing.helloworld.exe
.
Note: You might need to press Enter a couple of times initially to see the PowerShell prompt in the terminal. This issue should be fixed in a future release of Windows.
Modifying tasks.json
You can modify your
tasks.json
to build multiple C++ files by using an argument like '${workspaceFolder}*.cpp'
instead of ${file}
. This will build all .cpp
files in your current folder. You can also modify the output filename by replacing '${fileDirname}${fileBasenameNoExtension}.exe'
with a hard-coded filename (for example '${workspaceFolder}myProgram.exe'
).Debug helloworld.cpp
Next, you'll create a
launch.json
file to configure VS Code to launch the Microsoft C++ debugger when you press F5 to debug the program. From the main menu, choose Run > Add Configuration... and then choose C++ (Windows).You'll then see a dropdown for various predefined debugging configurations. Choose cl.exe build and debug active file.
VS Code creates a
launch.json
file, opens it in the editor, and builds and runs 'helloworld'.The
program
setting specifies the program you want to debug. Here it is set to the active file folder ${fileDirname}
and active filename with the .exe
extension ${fileBasenameNoExtension}.exe
, which if helloworld.cpp
is the active file will be helloworld.exe
.By default, the C++ extension won't add any breakpoints to your source code and the
stopAtEntry
value is set to false
. Change the stopAtEntry
value to true
to cause the debugger to stop on the main
method when you start debugging.Start a debugging session
- Go back to
helloworld.cpp
so that it is the active file. - Press F5 or from the main menu choose Run > Start Debugging. Before you start stepping through the source code, let's take a moment to notice several changes in the user interface:
- The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.
- The editor highlights the first statement in the
main
method. This is a breakpoint that the C++ extension automatically sets for you: - The Run view on the left shows debugging information. You'll see an example later in the tutorial.
- At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.
Step through the code
Now you're ready to start stepping through the code.
- Click or press the Step over icon in the debugging control panel until the
for (const string& word : msg)
statement is highlighted.The Step Over command skip over all the internal function calls within thevector
andstring
classes that are invoked when themsg
variable is created and initialized. Notice the change in the Variables window on the left. In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents ofmsg
are visible, however, because that statement has completed. - Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.
- Press Step over again to execute the
cout
statement. Note As of the March 2019 version of the extension, no output is displayed until the loop completes. - If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the
helloworld.cpp
tab in the code editor, putting the insertion point somewhere on thecout
statement inside the loop, and pressing F9. A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.Then press F5 to start execution from the current line in the standard library header. Execution will break oncout
. If you like, you can press F9 again to toggle off the breakpoint.
Set a watch
Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.
- Place the insertion point inside the loop. In the Watch window, click the plus sign and in the text box, type
word
, which is the name of the loop variable. Now view the Watch window as you step through the loop. - Add another watch by adding this statement before the loop:
int i = 0;
. Then, inside the loop, add this statement:++i;
. Now add a watch fori
as you did in the previous step. - To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.
C/C++ configurations
If you want more control over the C/C++ extension, you can create a
c_cpp_properties.json
file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).
This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called
c_cpp_properties.json
in the .vscode
folder.Visual Studio Code places these settings in
.vscodec_cpp_properties.json
. If you open that file directly, it should look something like this:You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.
Compiler path
The
compilerPath
setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful features like smart completions and Go to Definition navigation.The C/C++ extension attempts to populate
compilerPath
with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.The
compilerPath
search order is:- First check for the Microsoft Visual C++ compilerOpe
- Then look for g++ on Windows Subsystem for Linux (WSL)
- Then g++ for Mingw-w64.
If you have g++ or WSL installed, you might need to change
compilerPath
to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: 'C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe'.Reusing your C++ configuration
VS Code is now configured to use the Microsoft C++ compiler. The configuration applies to the current workspace. To reuse the configuration, just copy the JSON files to a
.vscode
folder in a new project folder (workspace) and change the names of the source file(s) and executable as needed.Troubleshooting
The term 'cl.exe' is not recognized
If you see the error 'The term 'cl.exe' is not recognized as the name of a cmdlet, function, script file, or operable program.', this usually means you are running VS Code outside of a Developer Command Prompt for Visual Studio and VS Code doesn't know the path to the
cl.exe
compiler.You can always check that you are running VS Code in the context of the Developer Command Prompt by opening a new Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`)) and typing 'cl' to verify
cl.exe
is available to VS Code.Next steps
- Explore the VS Code User Guide.
- Review the Overview of the C++ extension.
- Create a new workspace, copy your
.vscode
JSON files to it, adjust the necessary settings for the new workspace path, program name, and so on, and start coding!
This article introduces the features of the Visual Studio debugger in a step-by-step walkthrough. If you want a higher-level view of the debugger features, see First look at the debugger. When you debug your app, it usually means that you are running your application with the debugger attached. When you do this, the debugger provides many ways to see what your code is doing while it runs. You can step through your code and look at the values stored in variables, you can set watches on variables to see when values change, you can examine the execution path of your code, see whether a branch of code is running, and so on. If this is the first time that you've tried to debug code, you may want to read Debugging for absolute beginners before going through this article.
Although the demo app is C++, most of the features are applicable to C#, Visual Basic, F#, Python, JavaScript, and other languages supported by Visual Studio (F# does not support Edit-and-continue. F# and JavaScript do not support the Autos window). The screenshots are in C++.
In this tutorial, you will:
- Start the debugger and hit breakpoints.
- Learn commands to step through code in the debugger
- Inspect variables in data tips and debugger windows
- Examine the call stack
Prerequisites
Dev C++ Debug Crash
You must have Visual Studio 2019 installed and the Desktop development with C++ workload.
You must have Visual Studio 2017 installed and the Desktop development with C++ workload.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features..., which opens the Visual Studio Installer. The Visual Studio Installer launches. Choose the Desktop development with C++ workload, then choose Modify.
Create a project
First, you'll create a C++ console application project. The project type comes with all the template files you'll need, before you've even added anything!
- Open Visual Studio 2017.
- From the top menu bar, choose File > New > Project.
- In the New Project dialog box in the left pane, expand Visual C++ and then choose Windows Desktop. In the middle pane, choose Windows Console Application. Then name the project get-started-debugging.If you don't see the Console App project template, choose the Open Visual Studio Installer link in the left pane of the New Project dialog box. The Visual Studio Installer launches. Choose the .NET Core cross-platform development workload, and then choose Modify.
- Click OK.Visual Studio opens your new project.
- Open Visual Studio 2019.If the start window is not open, choose File > Start Window.
- On the start window, choose Create a new project.
- On the Create a new project window, enter or type console in the search box. Next, choose C++ from the Language list, and then choose Windows from the Platform list.After you apply the language and platform filters, choose the Console App template, and then choose Next.NoteIf you do not see the Console App template, you can install it from the Create a new project window. In the Not finding what you're looking for? message, choose the Install more tools and features link. Then, in the Visual Studio Installer, choose the Desktop development with C++ workload.
- In the Configure your new project window, type or enter get-started-debugging in the Project name box. Then, choose Create.Visual Studio opens your new project.
Create the application
- In get-started-debugging.cpp, replace all of the default code with the following code instead:
Start the debugger!
- Press F5 (Debug > Start Debugging) or the Start Debugging button in the Debug Toolbar.F5 starts the app with the debugger attached to the app process, but right now we haven't done anything special to examine the code. So the app just loads and you see the console output.In this tutorial, we'll take a closer look at this app using the debugger and get a look at the debugger features.
- Stop the debugger by pressing the red stop button (Shift + F5).
- In the console window, press a key and Enter to close the console window.
Set a breakpoint and start the debugger
- In the
for
loop of themain
function, set a breakpoint by clicking the left margin of the following line of code:name += letters[i];
A red circle appears where you set the breakpoint.Breakpoints are one of the most basic and essential features of reliable debugging. A breakpoint indicates where Visual Studio should suspend your running code so you can take a look at the values of variables, or the behavior of memory, or whether or not a branch of code is getting run. - Press F5 or the Start Debugging button , the app starts, and the debugger runs to the line of code where you set the breakpoint.The yellow arrow represents the statement on which the debugger paused, which also suspends app execution at the same point (this statement has not yet executed).If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. Otherwise, F5 continues running the app to the next breakpoint.Breakpoints are a useful feature when you know the line of code or the section of code that you want to examine in detail. For information on the different types of breakpoints you can set, such as conditional breakpoints, see Using breakpoints.
Navigate code in the debugger using step commands
Mostly, we use the keyboard shortcuts here, because it's a good way to get fast at executing your app in the debugger (equivalent commands such as menu commands are shown in parentheses).
- While paused in the
for
loop in themain
method, press F11 (or choose Debug > Step Into) twice to to advance to theSendMessage
method call.After pressing F11 twice, you should be at this line of code:SendMessage(name, a[i]);
- Press F11 one more time to step into the
SendMessage
method.The yellow pointer advances into theSendMessage
method.F11 is the Step Into command and advances the app execution one statement at a time. F11 is a good way to examine the execution flow in the most detail. (To move faster through code, we show you some other options also.) By default, the debugger skips over non-user code (if you want more details, see Just My Code).Let's say that you are done examining theSendMessage
method, and you want to get out of the method but stay in the debugger. You can do this using the Step Out command. - Press Shift + F11 (or Debug > Step Out).This command resumes app execution (and advances the debugger) until the current method or function returns.You should be back in the
for
loop in themain
method, paused at theSendMessage
method call. - Press F11 several times until you get back to the
SendMessage
method call again. - While paused at the method call, press F10 (or choose Debug > Step Over) once.Notice this time that the debugger does not step into the
SendMessage
method. F10 advances the debugger without stepping into functions or methods in your app code (the code still executes). By pressing F10 on theSendMessage
method call (instead of F11), we skipped over the implementation code forSendMessage
(which maybe we're not interested in right now). For more information on different ways to move through your code, see Navigate code in the debugger.
Navigate code using Run to Click
- Press F5 to advance to the breakpoint.
- In the code editor, scroll down and hover over the
std::wcout
function in theSendMessage
method until the green Run to Click button appears on the left. The tooltip for the button shows 'Run execution to here'.NoteThe Run to Click button is new in Visual Studio 2017. (If you don't see the green arrow button, use F11 in this example instead to advance the debugger to the right place.) - Click the Run to Click button .The debugger advances to the
std::wcout
function.Using this button is similar to setting a temporary breakpoint. Run to Click is handy for getting around quickly within a visible region of app code (you can click in any open file).
Restart your app quickly
Click the Restart button in the Debug Toolbar (Ctrl + Shift + F5).
When you press Restart, it saves time versus stopping the app and restarting the debugger. The debugger pauses at the first breakpoint that is hit by executing code.
The debugger stops again at the breakpoint you previously set inside the
for
loop.Inspect variables with data tips
Features that allow you to inspect variables are one of the most useful features of the debugger, and there are different ways to do it. Often, when you try to debug an issue, you are attempting to find out whether variables are storing the values that you expect them to have at a particular time.
- While paused on the
name += letters[i]
statement, hover over theletters
variable and you see it's default value,size={10}
. - Expand the
letters
variable to see its properties, which include all the elements that the variable contains. - Next, hover over the
name
variable, and you see its current value, an empty string. - Press F5 (or Debug > Continue) a few times to iterate several times through the
for
loop, pausing again at the breakpoint, and hovering over thename
variable each time to check its value.The value of the variable changes with each iteration of thefor
loop, showing values off
, thenfr
, thenfre
, and so on.Often, when debugging, you want a quick way to check property values on variables, to see whether they are storing the values that you expect them to store, and the data tips are a good way to do it.
Inspect variables with the Autos and Locals windows
- Look at the Autos window at the bottom of the code editor.If it is closed, open it while paused in the debugger by choosing Debug > Windows > Autos.In the Autos window, you see variables and their current value. The Autos window shows all variables used on the current line or the preceding line (Check documentation for language-specific behavior).
- Next, look at the Locals window, in a tab next to the Autos window.
- Expand the
letters
variable to show the elements that it contains.The Locals window shows you the variables that are in the current scope, that is, the current execution context.
Set a watch
- In the main code editor window, right-click the
name
variable and choose Add Watch.The Watch window opens at the bottom of the code editor. You can use a Watch window to specify a variable (or an expression) that you want to keep an eye on.Now, you have a watch set on thename
variable, and you can see its value change as you move through the debugger. Unlike the other variable windows, the Watch window always shows the variables that you are watching (they're grayed out when out of scope).
Examine the call stack
- While paused in the
for
loop, click the Call Stack window, which is by default open in the lower right pane.If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack. - Click F11 a few times until you see the debugger pause in the
SendMessage
method. Look at the Call Stack window.The Call Stack window shows the order in which methods and functions are getting called. The top line shows the current function (theSendMessage
method in this app). The second line shows thatSendMessage
was called from themain
method, and so on.NoteThe Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.The call stack is a good way to examine and understand the execution flow of an app.You can double-click a line of code to go look at that source code and that also changes the current scope being inspected by the debugger. This action does not advance the debugger.You can also use right-click menus from the Call Stack window to do other things. For example, you can insert breakpoints into specified functions, advance the debugger using Run to Cursor, and go examine source code. For more information, see How to: Examine the Call Stack.
Change the execution flow
- Press F11 twice to run the
std::wcout
function. - With the debugger paused in the
SendMessage
method call, use the mouse to grab the yellow arrow (the execution pointer) on the left and move the yellow arrow up one line, back tostd::wcout
. - Press F11.The debugger reruns the
std::wcout
function (you see this in the console window output).By changing the execution flow, you can do things like test different code execution paths or rerun code without restarting the debugger.WarningOften you need to be careful with this feature, and you see a warning in the tooltip. You may see other warnings, too. Moving the pointer cannot revert your application to an earlier app state. - Press F5 to continue running the app.Congratulations on completing this tutorial!
Next steps
In this tutorial, you've learned how to start the debugger, step through code, and inspect variables. You may want to get a high-level look at debugger features along with links to more information.