A debugger allows you to run your program with extra capabilities that allow you to stop the program and inspect where it is and see the values of variables. If there is an error, such as a memory fault, you can see where the error occurred.
An integrated development environment has a debugger built into it, and you can find out how to use it by reading the documentation for the development environment. Here, I describe a free-standing debugger called gdb that is available with Linux.
First, before using gdb, compile your program with option -g. That will cause information for the debugger to be written into the machine language translation of your program. After compiling your program, suppose that you have an executable file called myprog. Then issue command
gdb ./myprogThe debugger will start and give you a prompt asking what you want to do. To run the program, write what would be a command line for it, but replace the command with run. For example, gdb command
run stuff.txt >output.txtruns your executable program as if run by command
./myprog stuff.txt >output.txtexcept that the debugger is in control of it.
Typing control-C will not stop the program, but only pause it. Then gdb will show a prompt, asking you what you want to do. Here is a short list of commands that gdb allows.
|This is short for backtrace. It shows the run-time stack, with a line for each frame. If there are a lot of frames, it pauses after each pageful. Press a space to see the next page, or q to quit.|
|You are always inspecting a single frame. Initially, the current frame is the top one (frame 0). Command up moves to the next higher-numbered frame. Command up 2 moves up two frames. Use any positive integer after up|
|Command down is similar to up, but it moves down a frame (or a given number of frames).|
|Show the value of expression E. Gdb knows most of the syntax that C++ allows for expressions, but do not use function calls. Variables in the expression can either be variables in the current frame or global variables.|
|Run function-call expression E.|
|Stop the program each time it calls function fun.|
|Resume running the program after pausing it. You can use abbreviation cont.|
|Just type the enter key, without a command, to repeat the previous command.|
Ask for help. You will get a list of topics. Command
help topicdescribes commands under the given topic.