Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

How do I use the MinGW gdb debugger to debug a C++ program in Windows?

I have looked for documentation on this and found nothing. I have MinGW installed and it works great. I just don't know how to use the debugger.

Given some simple code, say in a file called "mycode.cpp":

int main()
{
    int temp = 0;

    for (int i = 0; i < 5; ++i)
        temp += i;

    return 0;
}

...how would I debug this. What are the commands that I use to debug code with MinGW and GDB in windows? Can I step through the code via the command line like in Visual Studio? If so what commands do I use to do that?

Are there any tutorials for using GDB out there? I couldn't find any, but if anyone could direct me to one that would be great too. I'm tired of writing tons of std::cout statements to debug complex code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first step is to compile your program with -g to include debugging information within the executable:

g++ -g -o myprog.exe mycode.cpp

Then the program can be loaded into gdb:

gdb myprog.exe

A few commands to get you started:

  • break main will cause the debugger to break when main is called. You can also break on lines of code with break FILENAME:LINENO. For example, break mycode.cpp:4 breaks execution whenever the program reaches line 4 of mycode.cpp.
  • start starts the program. In your case, you need to set breakpoints before starting the program because it exits quickly.

At a breakpoint:

  • print VARNAME. That's how you print values of variables, whether local, static, or global. For example, at the for loop, you can type print temp to print out the value of the temp variable.
  • step This is equivalent to "step into".
  • next or adv +1 Advance to the next line (like "step over"). You can also advance to a specific line of a specific file with, for example, adv mycode.cpp:8.
  • bt Print a backtrace. This is a stack trace, essentially.
  • continue Exactly like a "continue" operation of a visual debugger. It causes the program execution to continue until the next break point or the program exits.

The best thing to read is the GDB users' manual.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...