When your program doesn't work right, it usually has a "bug" in it, meaning there's something wrong with the program itself that is causing unexpected results or crashes. Diagnosing these bugs and fixing them is made easy by special tools called debuggers. In the case of Cygwin, the debugger is GDB, which stands for "GNU DeBugger". This tool lets you run your program in a controlled environment where you can investigate the state of your program while it is running or after it crashes. Crashing programs sometimes create "core" files. In Cygwin these are regular text files that cannot be used directly by GDB.
Before you can debug your program, you need to prepare your
program for debugging. What you need to do is add
-g to all the other flags you use when compiling
your sources to objects.
What this does is add extra information to the objects (they get much bigger too) that tell the debugger about line numbers, variable names, and other useful things. These extra symbols and debugging information give your program enough information about the original sources so that the debugger can make debugging much easier for you.
To invoke GDB, simply type gdb myapp.exe at the
command prompt. It will display some text telling you about itself,
(gdb) will appear to prompt you to enter
commands. Whenever you see this prompt, it means that gdb is waiting
for you to type in a command, like run or
help to get help on the commands you can type in, or
read the [GDB User's Manual] for a complete
description of GDB and how to use it.
If your program crashes and you're trying to figure out why it crashed, the best thing to do is type run and let your program run. After it crashes, you can type where to find out where it crashed, or info locals to see the values of all the local variables. There's also a print that lets you look at individual variables or what pointers point to.
If your program is doing something unexpected, you can use the break command to tell gdb to stop your program when it gets to a specific function or line number:
Now, when you type run your program will stop at that "breakpoint" and you can use the other gdb commands to look at the state of your program at that point, modify variables, and step through your program's statements one at a time.
Note that you may specify additional arguments to the run command to provide command-line arguments to your program. These two cases are the same as far as your program is concerned:
Example 4.4. Debugging with command line arguments
bash$myprog -t foo --queue 47
(gdb)run -t foo --queue 47