Sunday

How to debug your C++ code in CodeBlocks?

How to debug your C++ code in CodeBlocks?

You have to create a C++ project in CodeBlocks before you can start using the CodeBlocks debugger.

Use the following code.
File name: main.cpp
File content:
{{{{{
01 #include <iostream>
02 using namespace std;
03
04 int add(int a, int b);
05
06 int main(int argc, char* argv[])
07 {
08    int x=5, y=2, z;
09
10    z = add(x,y);
11
12    cout << "z value is " << z << endl;
13
14    return 0;
15 }
16
17 int add(int a, int b)
18 {
19    int c;
20
21    c = a + b;
22
23    return c;
24 }
}}}}}

Open the Watches window to watch certain variables during the execution of the program:
Menu > Debug > Debugging windows > Watches

You can start debugging at any line of your code:
-- Put the mouse cursor on line 8 which is the initialization values of variables
-- Press F4 to run to cursor
-- Press F7 to debug next line which is the add() function "z = add(x,y)"
-- While debugging, check all the variable values in the Watches window. You can see that x=5, y=2, and z is set to a random value
-- Press Shift+F7 to step into the body of the add() function
-- Press F7 to debug next line
-- In the watches window, you can know the local variable values of add() function where a=5, b=2, and c=7
-- Click on the "Toolbar > Debug > Step out" to step out from the add() function
-- Press F7 to debug next line
-- In the watches window, you can see that z=7
-- Press F7 to debug next line
-- Check out the command prompt window, you will get the program output "z value is 7"
-- Press F8 to continue debugging and your program will run to completion. Try not to select from the Debug menu "Break debugger" because you want your program to end naturally rather than aborting.

You can debug your program at multiple lines from all your marked out breakpoints:
-- Click on line 10 "z = add(x,y);" and press F5 to insert a breakpoint.
-- Click on line 21 "c = a + b;" and press F5 to insert a breakpoint.
-- Press F8 to start debugging. The debugger will pause at line 10 as the first breakpoint
-- In the watches window, you can see that x=5, y=2, and z is set to a random value
-- Press F8 to continue debugging at line 21 as the second breakpoint
-- Click on the "Toolbar > Debug > Step out" to step out from the add() function
-- Press F7 to debug next line
-- Press F7 to debug next line
-- Check out the command prompt window, you will get the program output "z value is 7"
-- Press F8 to continue debugging and your program will run to completion.

No comments:

If a hater attacked your age and not the goodness of you

Whether young or old, I've always been known what endures. I've known the very idea of people that were all created equal and deserv...