C + + @sublime GDB debugging

Source: Internet
Author: User
Tags gdb debugger

Text turn to from: http://www.cppblog.com/lucency/archive/2012/08/09/59214.html

Previously searched the internet for a long time to use sublime debugging C and C + + articles, but in vain; later sublime debug C + + is actually the same as the command line debug program, so even if the sublime gdb is installed, The same is to be based on the GDB manual that debugging steps.

Body:

This article is basically excerpted from the gdb manual , in addition to adding the actual code sample, so that you can see more clearly the execution of some commands. Of course, there are no GDB commands involved, just some of the usual ones.

The version of GdB I'm using here is 6.8. However, because it is a common command, there should be no problem with the old version. The operating system is Windows XP.

I. Overview
Two. GdB Start-Stop
Three. GDB command
Command syntax
Command completion
Get help
Four. Example 1
Breakpoint
Observation point
Snap Point
Delete Breakpoint
disabling breakpoints
Breakpoint Condition
Specify location
Stack
Data
Five Example 2
Six PostScript
I. Overview

The purpose of the debugger is to let you see the internal state of the program when it is running, or to see the cause of the program's exception when the program crashes. They can help in a few ways:

1) Start the program and affect the program's behavior according to your wishes

2) Let the program stop running when certain conditions occur

3) When the program stops, check what the program is doing

4) Change something in the program so that you can fix the bug at run time and then continue to test other issues.

GDB supports debugging in multiple languages, but the most mature should be C/s + +. Here is also a C + + program as an example to illustrate. If you want to know the support of other languages, you can read the GDB manual.

Two. GdB Start-Stop

The most common way to start GDB is:

GDB Program

Or when the program terminates abnormally:

GDB Program Core

Alternatively, you can attach to an already running process to debug it, just like this

GDB program PID

Of course, you can also set GDB's startup parameters at the command line, such as args:

Gdb-args gcc-o2-c foo.c

This allows you to debug GCC and pass the parameter "-o2-c foo.c" to GCC.

You can view all of GDB's options with Gdb-help.

To abort GdB's operation, you can enter quit or Q, or press the CTRL-D key combination.

Three. GDB Command command syntax

The GDB command is in the form: command [ARG1...ARGN]. Each command is a separate line. There is no limit to the length of the line (and, of course, it should not be too long).

Many GDB commands have abbreviated forms, such as break can be abbreviated as B.

If you press ENTER directly, GDB executes the command that was just executed.

If there is a # character in the command, then the character starting with # is treated as a comment. This is typically used in command files. There will be an introduction later.

Command completion

GDB has full complement functionality. function keys are <TAB>. For example, if you press the <TAB> key after entering the BRE, GDB will complete the break. If you enter only B, and then press <TAB>,GDB, this indicates that there are multiple commands starting with B. In this case, pressing once <tab>,gdb will output all commands starting with B. Here is the screen at this point:

If you just want to see a command that starts with a certain character, you can press <META>., instead of pressing two times <TAB>. In the absence of the <META> button on the computer, you can use the <ESC> button instead. This command is a bit troublesome to press, than to press two times <TAB> to be more trouble, if not afraid of <TAB> key is bad, I suggest you still press <TAB>.

Command completion can be used for GDB commands, GdB subcommands, symbolic names in programs (such as function names, and so on).

When debugging a C + + program, it is almost certain that the problem is overloaded functions. For example, when setting a breakpoint, assume that there are two functions named Overload, and in order to differentiate the function, it is necessary to add the function parameter type (name plus argument list as a logical word). In order for GDB to use parentheses around the argument list as part of the word, it is necessary to enclose the function in single quotation marks. See:

Get help

After you start GDB, you can enter a command to get a list of GDB commands. Note that at this point each entry of the output is a class of commands. Last Picture:

After you get the command category, you can use the command Help class to get all of these commands. :

Only part of the breakpoints command is shown in the figure above.

Other help-related commands are:

A) Help command

The Help information used to display command commands.

b) Apropos args

The args here can make regular expressions. Displays a brief description of all the commands that match args.

c) Complete args

Displays all commands that begin with args.

There are two other useful commands: info and show .

A) Info

Used to display information about the program being debugged. For example, the argument passed to the current function-info args, or the value of the current register-info registers, or the breakpoint-info breakpoints can be viewed. You can use Help info to view the description of info.

b) Show

This command is used to display gdb information. That is, some of GDB's property values. You can use Help show to view the assistance information. This command should usually be used in conjunction with set (to set GDB properties).

Well, now for GDB should have a general understanding of, below we will take a few small examples to verify the effect of some common commands. Let ' s go!

Four. Example 1

First of all, in order to efficiently use GDB's functionality, you need to compile the program with the-G option, this option will add debugging information to the executable file.

Here's a sample file, including three: Gdb.h, Gdb.cpp, Test.cpp

Gdb.h

#ifndef _gdb_h
#define _GDB_H 1

Class GDB
{
Public
explicit gdb (int v);
void overload (int one);
void overload (int one, int);
void catch_ex (int ex); exception
void Loop ();
Private
int value;
int array[10];
};

#endif

Gdb.cpp

#include "Gdb.h"
#include <iostream>
using namespace Std;

Gdb::gdb (int v)
{
Value = V;
for (int i=0; i<10; i++)
{
Array[i] = i;
}
}

void Gdb::overload (int one)
{
cout<< "function overload with one parameter:" <<one<<endl;
}

void Gdb::overload (int one, int)
{
cout<< "function overload with" Paremeters: "<<one<<" "<<two<<endl;
}

void Gdb::loop ()
{
int loop_array[10];
for (int i=0; i<10; i++)
{
Loop_array[i] = i;
}

int v=3;
v=3;
v=4;
}

void gdb::catch_ex (int ex)
{
int e = ex;
Try
{
if (e <= 0)
{
Throw e;
}
Else
{
cout<< "function catch_ex:" <<ex<<endl;
}
}
catch (int x)
{
cout<< "Exception:" <<x<<endl;
}
}

Test.cpp

#include "Gdb.h"

int main ()
{
GDB g (5);
G.overload (1);
G.overload (1, 2);
G.loop ();

G.CATCH_EX (3);
G.CATCH_EX (-1);

return 0;
}

OK, now start debugging. Start GDB First, specifying the executable file you want to debug. As already mentioned, you can simply use the GDB program to start. Alternatively, you can start GDB first, and then use the file command to specify the files you want to debug. The following is the screen that starts GDB only:

Now specify the files to debug with the file command:

You can then run the program with the run or r command. Before you run, you may need to set some information for the program, which has four kinds of information:

1) Program Parameters

The parameters of the program can be set using the set args command. After setting, you can use show args to see if the settings are correct. If set args is followed by no arguments, the arguments passed to the program are empty.

2) environment

The environment here is the environment variables that are set in the System/user profile, such as home, path, and so on. GDB provides a way to change the values of these variables at debug time so that you do not have to exit GDB to reset them when needed. The commands provided by GDB are:

A) path directory -Add directory to the environment variable path. Note that the change to path is only valid for the test program, and the path used by GDB will not change. 1

b) Show paths--Displays the value of path.

c) Show environment [varname]-Displays the value of the environment variable varname, and displays the values of all environment variables if you do not specify VarName.

d) Set Environment varname [= value]--Sets the value of the environment variable varname. This change is only valid for the debug program. If value is not supplied, the value of varname is set to null.

e) unset Environment varname -Removes the variable varname passed to the program from the environment.

3) Working directory

When you start the GDB debugger, the program being debugged inherits the working directory from GDB. Of course GDB also provides commands to modify the working directory:

A) CD directory -set directory as the new working directory.

b) PWD-Displays the current working directory.

4) standard input and output

Have not found in windows this thing has what use, and now there is no Linux available, not much to say. See the GDB Handbook yourself if you need it. Let me simply copy the manual.

In GdB, you can redirect the input and output of the Run command to a file or to another terminal. You can also set up devices that are input and output by the debugger through the TTY command. The command format is:

TTY terminal or set Inferior-tty terminal.

The TTY is the alias of set Inferior-tty.

Knock it off!

Above we have started the program, but also know how to run the program. However, if you execute the Run command directly you will find that the program is running at the end. What if you want to stop the program from running when a line or function is called, or when the value of a variable/expression changes, or when something happens--such as throwing an exception, loading a dynamic library, or creating a child process?

With GDB, everything will be all right:), using the following three powerful weapons, you can stop the program arbitrarily. Careful, everyone, I will sacrifice these three treasures, they are:

Breakpoint

Breakpoints are specifying a location that will stop the program from running to this location (and, of course, conditional breakpoints can be set, and the program will stop when it is run to the specified location), which makes it easier to observe the internal state of the program. Breakpoint-related commands are mainly:

A) break Location

Set a breakpoint at the location located at the specified position, where it can be a function name, a line number, an instruction address, and so on (see here for information on how to specify locations).

b) Break

If you do not specify any parameters, break sets a breakpoint at the next instruction in the selected stack frame.

c) Break ... if cond

Sets a conditional breakpoint. Each time the breakpoint is reached, the expression cond evaluated, only if the result is not 0, the program will stop at this breakpoint.

d) tbreak args

Sets a breakpoint that only takes effect once. Args have the same meaning as the parameters in the break command (that is, it can be location, empty, or condition).

e) hbreak args

Sets a hardware breakpoint.

f) thbreak args

Sets a hardware breakpoint that takes effect only once.

g) Rbreak regex

Sets a breakpoint on all functions that match the regular expression regex .

h) Info breakpoints [n]

i) info break [n]

j) Info watchpoints [n]

The above three commands list the current breakpoints, observer points, and snap points, and if you specify parameter n, only the nth information is listed.

Let's test it out. First start the program with GDB, assuming we want to add a breakpoint in Test.cpp's G.overload (1) line, execute the command: B test.cpp:6, after execution:

You can then use the info break and other commands to view the breakpoint information:

Then we run the program and see what the effect is.

See, the program stops at the line where the breakpoint is located. You can use where or frame to view the current stack frame information, or you can use Print to view some variable or expression information, or info args to view parameter information, and so on.

Other commands you can try it on your own.

Sometimes we are not sure where to add breakpoints, for example, when we want to stop the program when a variable is changed or read or written, perhaps because there are more places to access the variable, it is troublesome to add a breakpoint to each place, and it is possible to omit it, so we need to rely on another powerful command. That's the point of observation.

Observation point

The Observer is a special kind of breakpoint, and if you specify an observer point for a variable or expression, GDB stops executing the program when its value is read/write. You don't need to specify exactly where the observer is in your program, as you would when you set a breakpoint. The commands related to the Observer point are:

A) watch expr [thread threadnum]

Set an observer point for expr . When the value of expr is changed, GDB stops the program from running.

If thread threadnum is specified, the program stops only if threadnum changes the value of expr .

b) Rwatch expr [thread threadnum]

Set a read observation point to expr . When the program reads the value of expr , GDB stops the program from running.

c) Awatch expr [thread threadnum]

Set an access observer point to expr . When the program reads or writes expr , GDB stops the program from running.

D) Info watchpoints

Displays all breakpoints, observer points, snap points. Same as info break.

Let's take a look at the use of observation points.

First we set a breakpoint in the G.loop () line, and then run it here. Step enters the loop () function. The execution of this sequence of commands is as follows:

At this point we have entered the loop () function, and now we have set up several observation points. Sets the command sequence and finishes the effect as small as:

You can see that there are 5 stop points, the first two of which are the breakpoints we set, and the next three are the observation points. Watch, Rwatch and Awatch, respectively. There is also a place where hardware observation points are x86 on the default.

OK, let's run it and try it.

When the first observer is reached, the program stops running and prints out the old and new values of the variable, as well as the location of the observer point.

Let's go ahead and see what happens when we encounter the next observation point.

The program stops at the third observation point (the second observer is the Reading observer), and the new and old values of the variable and the position of the observer are also printed. The second observer, because it is a reading observer, does not read the variable anywhere in the program, so it is skipped when it is running. To see the effect of reading the observation point, we then set up a reading observation point:

I is an iterator within the loop that will be copied to the Loop_array[i] variable, which will be read. As you can see, the program stops running, outputting the value of I. Note: Each read to I will cause the program to stop. Here is the output after executing the Continue command two times:

The content of the observation point is about the same. Another thing to note is that the Watch command sets the observer point to stop the program from running if the value of the variable or expression is changed, and if it is only written, but the value does not change, the program does not stop.

The above has been said to break point, observation point, and in some cases, these two stops are not the most effective way. For example, in the C + + program to run out of the abnormal time to stop the program, when the breakpoint is not effective, because the program may be a lot of exception to deal with the place, if one set breakpoints, it is too troublesome (of course, if only a few exceptions, with breakpoints can not be used, even more flexible);

In this case, the capture point needs to be used.

Snap Point

Snap points are also a special kind of breakpoint that can cause a program to stop running when an event occurs, such as a C + + exception, or to load a dynamic library, create a child process, and so on. The command that sets the snap point is a catch.

Catch Event

Where the event can be:

A) throw

C + + throws an exception.

b) Catch

C + + catches exceptions.

c) exception

Ada exception.

D) Exception unhandled

Unhandled exception in the program.

E) Assert

The ADA assertion failed.

f) Exec

Calls to EXEC (available only in HP-UX and Gnu/linux).

g) Fork

Calls to fork (available only in HP-UX and Gnu/linux).

h) vfork

Calls to Vfork (available only in HP-UX and Gnu/linux).

i) load

Dynamically load shared libraries (available only in HP-UX).

j) Load libname

Dynamically load Shared library libname (available only in HP-UX).

k) Unload

Unload a shared library that is already loaded (available only in HP-UX).

L) Unload libname

Unload the shared library Libname that has been loaded (available only in HP-UX).

There is also a command to set a snap point that only takes effect once: Tcatch event .

Let's look at the use of snap points below.

First in Vtest.cpp's G.CATCH_EX (-1); Set a breakpoint and run it to enter this function.

Now let's set up a snap point. Continue running:

You can see that the program stopped at the point where the exception was thrown.

Delete Breakpoint

When the breakpoint is no longer needed, it should be deleted, or each execution to the breakpoint location program to stop, will drive people crazy. There are two commands to delete a breakpoint: clear and delete.

A) Clear [ location]

If you do not specify a location, delete any breakpoints on the next instruction that you want to execute in the selected stack frame. If you select the most internal stack frame (that is, the stack frame of the function that is currently executing), clear removes the breakpoint that just made the program stop. A description of location can be seen here.

b) Delete [breakpoints] [ range ...]

Deletes all breakpoints , observers, and snap points for the specified range range. If you do not specify a parameter range , all stop points are deleted. The range specified here is the breakpoint number range. You can use info break to view breakpoint information.

disabling breakpoints

You can use the Disable command if you do not want to delete the breakpoint and just want to invalidate it temporarily. The Disable command is in the following form:

A) disable [breakpoints] [ range ...]

Invalidates the breakpoint within the specified range range . If you do not specify a range , all breakpoints are invalidated.

The command that makes the breakpoint effective is enable, in the form of:

A) enable [breakpoints] [ range ...]

Causes a breakpoint or all breakpoints in the specified range range to take effect.

b) enable [breakpoints] once range...

Causes a breakpoint within the specified interval to take effect once.

c) enable [breakpoints] Delete range...

Causes a breakpoint within the specified interval to take effect once, and then delete.

Breakpoint Condition

The breakpoint condition makes the breakpoint valid only if the appropriate condition is met. The conditional expression here is the same as the syntax for the logical expression of the language used in the program, such as A==b or x&&y in a C + + language.

The breakpoint condition can be specified when a breakpoint is set, or it can be set or changed by the condition command after the breakpoint is set. The form of condition is:

a) Condition bnum expression

Sets the condition that expression bnum for the stop point.

b) Condition bnum

Removes the condition of the stop point bnum .

There is also a command that allows GDB to ignore breakpoints for a certain number of times, in the form of:

A) ingore bnum Count

Specify location

Many GDB commands accept a parameter that specifies the location of the program. There are several ways to specify the location:

A) linenum

The line number of the current source file.

b) -offset

The line that precedes the current row and is offset from the current line interval. The current row can be determined by using the List command, where the last line printed is the current row, or, for a breakpoint command, the location of the selected stack frame where the program stops executing is the current row.

c) +offset

The row following the current line, offset from the current line interval.

d) Filename:linenum

The line linenumin the source file filename .

E) function

function functions in the current source file.

f) Filename:function

function functions in the source file filename .

g) * address

Specifies the program address. The commonly used address forms are:

Expression--valid expressions in the current language.

funcaddr --The address of the function. The function name is in C/s + +.

' filename ':: funcaddr --the function address funcaddrin the source file filename .

The back is too lazy to write, temporarily put first. found that even copying documents, the content of more is a very tiring job. Alas, lazy, not ...

Stack

You want to add

Data

You want to add

Five Example 2

You want to add

Six PostScript

This article just picked up some of the most commonly used in gdb, and is only a small part of the most common things, interested in or need to be able to directly see the GDB document, can be found here.

1. Do not know whether it is because of Windows and Linux system, after starting the program with GDB, after executing show paths output: Executables and Object file path:. This means that the value of the output is empty.

[email protected] GDB debugging

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.