Reputation: 53
I just started programming in c, and I want to test some code. So, I need to know the value of a variable at a specific point in the program which I already know.
while searching I saw many people are using gdb and core dump but most of the examples I found they use it to debug the code if there is a crash. in my case, I don't want to terminate the execution, I just want to save/know the value of a specific variable at a specific point.
for example:
if I have this piece of code:
int func(int x){
x = 3 * x;
if(x > 0){
x = x % 4;
/* I want to know the value of x at this point*/
}
else {
x = x + 1;
/* I want to know the value of x at this point*/
}
return x;
}
if the user enters the value, I want to know what will be the value of x inside the block of (if) after the calculation.
UPDATE: to clarify my question, I have a big code and I want to test the complete package and I want to write a function that tells me what is the stored value at this program point.
Upvotes: 0
Views: 474
Reputation: 447
GDB is the best tool for you. While the program is in execution you can see the values of the variables. Please follow the below steps:
compile your program with -g flag.
gcc -g program.c -o output
Now run your program with gdb:
gdb output
In Gdb command line set a breakpoint at 'main' by using:
(gdb) b main
or use below one to set a breakpoint at a particular line.
(gdb) b line_number
now enter 'r' to run the program.
(gdb) r
type 'n' and press enter to go to next line
(gdb) n
type 'step' to step into a function:
(gdb) step
Examine the variable value by using
(gdb) print variable-name
Keep the breakpoint at 'line no' where you want to see the value of a variable and use 'print variable-name
' to view the value.
Please take this as a reference for more GDB commands: http://www.yolinux.com/TUTORIALS/GDB-Commands.html
Hope this answer will help you to debug your code.
Upvotes: 2
Reputation: 58
Another approach expanding on using printf is to use debugging macros or functions. E.g. see:
https://github.com/jleffler/soq/blob/master/src/libsoq/debug.c
Something like this can be used to allow dynamically enabling debugging for some use cases of your function and then disable it again so you don't get too much output to have to work through when debugging your code.
Upvotes: 0
Reputation: 67476
Use the debugger (install any C IDE like Eclipse CDT and you will not have to configure anything)
You can even do the debugging online https://www.onlinegdb.com/
Upvotes: 0
Reputation: 411
I think You can use something like this
printf("%d\n",x);
after each expression with
x= ...
in Your function. Or You can use fprintf to write values in a file instead printf if You don't want to output values to the console.
Upvotes: 1