C language programming in linux ----- getting started with GBD
Source: Internet
Author: User
C language programming in linux ----- getting started with GBD -- general Linux technology-Linux programming and kernel information. For more information, see the following. <一> GDB Overview
GDB is a powerful UNIX program debugging tool released by the GNU open-source organization. Maybe you prefer the graphical interface, such as VC, BCB, and other IDE debugging methods,
However, if you are working on a UNIX platform, you will find that the GDB debugging tool has more powerful functions than the visual debugger of VC and BCB.
This is the so-called "have an inch, have a small size and have a short size.
In general, GDB helps you complete the following four functions:
1. Start your program and run it as needed according to your custom requirements.
2. The program to be debugged can be stopped at the breakpoint you specified. (The breakpoint can be a conditional expression)
3. When the program is stopped, you can check what happens in your program.
4. dynamically change the execution environment of your program.
From the above point of view, GDB is similar to a general debugging tool and basically completes these functions. However, in details, you will find that GDB is a powerful debugging tool,
You may be used to graphical debugging tools, but sometimes command line debugging tools have functions that cannot be completed by graphical tools. Let's look at it one by one.
A debugging example
Source program: tst. c
1 # include
2
3 int func (int n)
4 {
5 int sum = 0, I;
6 for (I = 0; I 7 {
8 sum + = I;
9}
10 return sum;
11}
12
13
14 main ()
15 {
16 int I;
17 long result = 0;
18 for (I = 1; I <= 100; I ++)
19 {
20 result + = I;
21}
22
23 printf ("result [1-100] = % d \ n", result );
24 printf ("result [1-250] = % d \ n", func (250 ));
25}
Compile and generate the execution file: (in Linux)
Hchen/test> gcc-g tst. c-o tst # note that the-g parameter must be included. Refer to the gcc User Manual to understand this parameter.
Debug with GDB:
Hchen/test> gdb tst <---------- start GDB
GNU gdb 5.1.1
Copyright 2002 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
Welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-suse-linux "...
(Gdb) l 1 <-------------------- l command is equivalent to list, the original code is obtained from the first line.
1 # include
2
3 int func (int n)
4 {
5 int sum = 0, I;
6 for (I = 0; I 7 {
8 sum + = I;
9}
10 return sum;
(Gdb) <-------------------- press enter to repeat the previous command
11}
12
13
14 main ()
15 {
16 int I;
17 long result = 0;
18 for (I = 1; I <= 100; I ++)
19 {
20 result + = I;
(Gdb) break 16 <-------------------- set the breakpoint, at the source program line 16th.
Breakpoint 1 at 0x8048496: file tst. c, line 16.
(Gdb) break func <-------------------- sets the breakpoint at the entry of the function func.
Breakpoint 2 at 0x8048456: file tst. c, line 5.
(Gdb) info break <-------------------- view the breakpoint information.
Num Type Disp Enb Address What
1 breakpoint keep y 0x08048496 in main at tst. c: 16
2 breakpoint keep y 0x08048456 in func at tst. c: 5
(Gdb) r <--------------------- run the program, short for the run Command
Starting program:/home/hchen/test/tst
Breakpoint 1, main () at tst. c: 17 <---------- stop at the Breakpoint.
17 long result = 0;
(Gdb) n <--------------------- execute a single statement. The next command is short for execution.
18 for (I = 1; I <= 100; I ++)
(Gdb) n
20 result + = I;
(Gdb) n
18 for (I = 1; I <= 100; I ++)
(Gdb) n
20 result + = I;
(Gdb) c <--------------------- to continue running the program, the continue command is abbreviated.
Continuing.
Result [1-100] = 5050 <---------- program output.
Breakpoint 2, func (n = 250) at tst. c: 5
5 int sum = 0, I;
(Gdb) n
6 for (I = 1; I <= n; I ++)
(Gdb) p I <--------------------- print the value of variable I. The print command is short.
$1 = 134513808
(Gdb) n
8 sum + = I;
(Gdb) n
6 for (I = 1; I <= n; I ++)
(Gdb) p sum
$2 = 1
(Gdb) n
8 sum + = I;
(Gdb) p I
$3 = 2
(Gdb) n
6 for (I = 1; I <= n; I ++)
(Gdb) p sum
$4 = 3
(Gdb) bt <--------------------- view the function stack.
#0 func (n = 250) at tst. c: 5
#1 0x080484e4 in main () at tst. c: 24
#2 0x400409ed in _ libc_start_main () from/lib/libc. so.6
(Gdb) finish <--------------------- exit the function.
Run till exit from #0 func (n = 250) at tst. c: 5
0x080484e4 in main () at tst. c: 24
24 printf ("result [1-250] = % d \ n", func (250 ));
Value returned is $6 = 31375
(Gdb) c <--------------------- continue to run.
Continuing.
Result [1-250] = 31375 <---------- program output.
Program exited with code 027. <-------- the Program exits and debugging is complete.
(Gdb) q <--------------------- exit gdb.
Hchen/test>
Well, with the above perceptual knowledge, let's get to know gdb systematically.
<二> Use GDB
Generally, GDB mainly debugs C/C ++ programs. To debug a C/C ++ program, we must add the debugging information to the executable file during compilation.
This can be done using the-g parameter of the compiler (cc/gcc/g ++. For example:
> Gcc-g hello. c-o hello
> G ++-g hello. cpp-o hello
Without-g, you will not be able to see the function name and variable name of the program, instead of the runtime memory address. After you use-g to add debugging information,
After successfully compiling the target code, let's see how to debug it with gdb.
The following methods are used to start GDB:
1. gdb
Program is your execution file, which is usually in the directory of course.
2. gdb Core
Debug a running program and core file with gdb. The core is the file generated after the core is dumped after the program is illegally executed.
3. gdb
If your program is a service program, you can specify the process ID when the service program runs. Gdb automatically attach and debug it.
The program should be searched in the PATH environment variable.
When GDB is started, you can add some GDB start switches. For details about the switches, you can use gdb-help to view them. Here are some common parameters:
-Symbols
-S
Read the symbol table from a specified file.
-Se file
Read the symbol table information from the specified file and use it in the executable file.
-Core
-C
Core dump core File during debugging.
-Directory
-D
Add the search path of a source file. The default search PATH is the PATH defined by PATH in the environment variable.
After starting gdb, you will be brought into the debugging environment of gdb. You can use the gdb command to start debugging the program. The command of gdb can be viewed using the help Command, as shown below:
/Home/hchen> gdb
GNU gdb 5.1.1
Copyright 2002 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
Welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-suse-linux ".
(Gdb) help
List of classes of commands:
Aliases -- Aliases of other commands
Breakpoints -- Making program stop at certain points
Data -- Examining data
Files -- Specifying and examining files
Internals -- Maintenance commands
Obscure -- Obscure features
Running -- Running the program
Stack -- Examining the stack
Status -- Status inquiries
Support -- Support facilities
Tracepoints -- Tracing of program execution without stopping the program
User-defined -- User-defined commands
Type "help" followed by a class name for a list of commands in that class.
Type "help" followed by command name for full documentation.
Command name abbreviations are allowed if unambiguous.
(Gdb)
Gdb has many commands, which are divided into many types by gdb. The help Command is just an example of the command type of gdb. If you want to view the commands in the Command type,
You can use the help <class> command, for example, help breakpoints, to view all the commands for setting breakpoints. You can also directly help To view the help of the command.
In gdb, when you enter a command, you do not need to execute a full command. You only need to use the first few characters of the command. Of course,
The first few characters of a command should mark a unique command. in Linux, you can press the TAB key twice to complete the full name of the command,
If there are duplicates, gdb will take it as an example.
Example 1: Set a breakpoint when entering the function func. You can enter break func or B func.
(Gdb) B func
Breakpoint 1 at 0x8048458: file hello. c, line 10.
Example 2: Press B twice to press the TAB key. You will see all the commands for B headers:
(Gdb) B
Backtrace break bt
(Gdb)
Example 3: only remember the prefix of the function, which can be as follows:
(Gdb) B make _ <按tab键>
(Press the TAB key again and you will see :)
Make_a_section_from_file make_environ
Make_abs_section make_function_type
Make_blockvector make_pointer_type
Make_cleanup make_reference_type
Make_command make_symbol_completion_list
(Gdb) B make _
GDB will show you all the functions starting with make.
Example 4: When debugging a c ++ program, the function name can be the same. For example:
(Gdb) B 'bubble (M -?
Bubble (double, double) bubble (int, int)
(Gdb) B 'bubble (
You can view all the overload functions and parameters in C ++. (Note: M -? And press the TAB key twice)
To exit gdb, you only need to send quit or q for short.
Running UNIX shell programs in GDB
In the gdb environment, you can execute the UNIX shell command and use the gdb shell command to complete it:
Shell
Call the UNIX shell to execute The unix shell defined in the environment variable shell will be used for execution. If the SHELL is not defined, use the UNIX standard shell:/bin/sh. (Use command.comor cmd.exe in Windows)
Another gdb command is make:
Make
You can execute the make command in gdb to build your own program again. This command is equivalent to "shell make ".
Run the program in GDB
When gdb After you start gdb, gdb searches the PATH and the current directory. . To check whether gdb reads the source file, run the l or list command to check whether gdb can list the source code.
In gdb, run the r or run command. For program running, you may need to set the following four things.
1. program running parameters.
Set args can Specify runtime parameters. (For example, set args 10 20 30 40 50)
Run the show args command to view the set running parameters.
2. Running environment.
Path You can set the program running path.
Show paths to view the program running path.
Set environment varname [= value] To set environment variables. For example, set env USER = hchen
Show environment [varname] to view environment variables.
3. working directory.
Cd It is equivalent to the cd command of shell.
Pwd displays the current directory.
4. input and output of the program.
Info terminal shows the terminal mode used by your program.
Use the redirection control program output. For example, run> outfile
The tty command can be a terminal device that writes input and output data. For example, tty/dev/ttyb.
You can use either of the following methods to debug a running program:
1. Run ps on UNIX to view the PID (process ID) of the running program, and then use gdb A running program is mounted in PID format.
2. Use gdb first Associate the source code with gdb, and use the attach command in gdb to mount the PID of the process. Use detach to cancel the attached process.
Pause/resume program running
In the debugging program, it is necessary to pause the running of the program. GDB can conveniently pause the running of the program. You can set where the program stops and under what conditions,
When receiving a signal, wait. This allows you to view runtime variables and processes.
When the process is stopped by gdb, you can use info program to check whether the program is running, process number, and reason for suspension.
In gdb, we can use the following pause Methods: BreakPoint, WatchPoint, CatchPoint ),
Signal and Thread Stops ). To resume the program running, run the c or continue command.
1. Set a BreakPoint)
We use the break command to set breakpoints. There are several ways to set breakpoints on the front:
Break
Stops when you enter the specified function. In C ++, you can use the class: function or function (type, type) format to specify the function name.
Break
Stops at the specified row number.
Break + offset
Break-offset
Stop the offset row before or after the current row number. Offiset is a natural number.
Break filename: linenum
Stop at the linenum line of the source file filename.
Break filename: function
Stop at the entrance of the function of the source file filename.
Break * address
Stop at the memory address where the program runs.
Break
If the break command does not have a parameter, it indicates that it stops at the next command.
Break... if
... It can be the preceding parameter. condition indicates the condition and stops when the condition is set. For example, you can set break if I = 100 in the Environment body to stop the program when I is 100.
When viewing breakpoints, you can use the info command as follows: (Note: n indicates the breakpoint number)
Info breakpoints [n]
Info break [n]
2. Set the WatchPoint)
An observation point is usually used to check whether the value of an expression (a variable is also an expression) has changed. If the value changes, stop the program immediately. We have the following methods to set observation points:
Watch
Set an observation point for the expression (variable) expr. When the expression value changes, stop the program immediately.
Rwatch
When the expression (variable) expr is read, stop the program.
Awatch
When the value of an expression (variable) is read or written, stop the program.
Info watchpoints
Lists all the observed points currently set.
3. Set a capture point)
You can set capture points to catch up with some events when the program is running. For example, load the Shared Library (Dynamic Link Library) or C ++ exception. Set the capture point format:
Catch
When an event occurs, stop the program. Event can be the following content:
1. throw an exception thrown by C ++. (Throw is the keyword)
2. catch an exception caught by C ++. (Catch is a keyword)
3. When exec is called by the system. (Exec is a keyword, which is currently only useful in HP-UX)
4. When fork calls fork. (Fork is a keyword, which is currently only useful in HP-UX)
5. When vfork calls vfork. (Vfork is a keyword, which is currently only useful in HP-UX)
6. load or load Load the Shared Library (dynamic link library. (Load is a keyword, which is currently only useful in HP-UX)
7. unload or unload When you detach a shared library (dynamic link library. (Unload is a keyword, which is currently only useful in HP-UX)
Tcatch
Set only one capture point. When the program stops, the point is automatically deleted.
4. Maintenance stop point
The above describes how to set the stop point of the program. The stop point in GDB is also the three types mentioned above. In GDB, if you think the predefined stop point is useless,
You can use the delete, clear, disable, and enable commands for maintenance.
Clear
Clear all defined stop points.
Clear
Clear
Clear all stop points set on the function.
Clear
Clear
Clear all stop points set on the specified row.
Delete [breakpoints] [range...]
Delete the specified breakpoint. breakpoints is the breakpoint number. If no breakpoint number is specified, all breakpoints are deleted. Range indicates the range of the breakpoint number (for example, 3-7 ). The short command is d.
A better method than deleting is disable stop point. GDB does not delete the stop point after disable. When you still need it, enable it, just like the recycle bin.
Disable [breakpoints] [range...]
The stop point specified by disable. breakpoints is the stop point number. If nothing is specified, it indicates all the stop points of disable. The abbreviated command is dis.
Enable [breakpoints] [range...]
The stop point specified by enable. breakpoints is the stop point number.
Enable [breakpoints] once range...
Enable: The stop point specified by enable is automatically disable by GDB immediately after the program is stopped.
Enable [breakpoints] delete range...
The stop point specified by enable is automatically deleted by GDB immediately after the program is stopped.
5. Stop condition maintenance
As mentioned earlier, when setting breakpoints, we mentioned that you can set a condition. When a condition is set, the program stops automatically. This is a very powerful function,
Here, I want to talk about the maintenance commands related to this condition. Generally, we use the if keyword to set a condition for a breakpoint, followed by its breakpoint condition.
In addition, after the conditions are set, we can use the condition command to modify the breakpoint conditions. (Only the break and watch commands support if. catch currently does not support if)
Condition
Modify the Stop Condition of breakpoint number bnum to expression.
Condition
Clear the stop condition with the breakpoint number bnum.
There is also a special maintenance command ignore, you can specify the number of times when the program runs, ignore the stop condition.
Ignore
Indicates that the count of the Stop condition with the breakpoint number bnum is ignored.
6. Set the running command for the stop point
We can use the command provided by GDB to set the running command of the stop point. That is, when the running program is stopped,
We can make it automatically run some other commands, which is advantageous for automatic debugging. It provides powerful support for automated debugging Based on GDB.
Commands [bnum]
... Command-list...
End
For the breakpoint bnum, write a command list. When the program is stopped by the breakpoint, gdb runs the commands in the command list in sequence.
For example:
Break foo if x> 0
Commands
Printf "x is % d \ n", x
Continue
End
The breakpoint is set in function foo. the breakpoint condition is x> 0. If the program is disconnected, that is, once the value of x is greater than 0 in function foo, GDB automatically prints the value of x and continues to run the program.
If you want to clear the command sequence on the breakpoint, you only need to simply execute the commands command and directly create an end.
VII. breakpoint menu
In C ++, a function with the same name may appear multiple times (function overloading). In this case,
Break You cannot tell GDB which function to stop. Of course, you can use break That is
Tell GDB about the parameter type of the function to specify a function. Otherwise, GDB will list a breakpoint menu for you to choose the breakpoint you need.
You only need to enter the number in your menu list. For example:
(Gdb) B String: after
[0] cancel
[1] all
[2] file: String. cc; line number: 867
[3] file: String. cc; line number: 860
[4] file: String. cc; line number: 875
[5] file: String. cc; line number: 853
[6] file: String. cc; line number: 846
[7] file: String. cc; line number: 735
> 2 4 6
Breakpoint 1 at 0xb26c: file String. cc, line 867.
Breakpoint 2 at 0xb344: file String. cc, line 875.
Breakpoint 3 at 0 xafcc: file String. cc, line 846.
Multiple breakpoints were set.
Use the "delete" command to delete unwanted
Breakpoints.
(Gdb)
It can be seen that GDB lists all the after overload functions. You can select the list number. 0 indicates that the breakpoint is not set. 1 indicates that all functions are set to the breakpoint.
8. Resume program running and single-step debugging
When the program is stopped, you can run the "continue" command to restore the program until the program ends or the next breakpoint arrives.
You can also use the step or next command to track a single step.
Continue [ignore-count]
C [ignore-count]
Fg [ignore-count]
Resume the program running until the program ends or the next breakpoint arrives. Ignore-count indicates the number of breakpoints that are ignored. The continue, c, and fg commands all share the same meaning.
Step
One-step tracking. If a function is called, it enters the function. The premise for entering the function is that the function is compiled with debug information. Similar to step in VC and other tools. You can add count or not. If you do not add count, it means to execute the count command next to it, and then stop.
Next
Similarly, if a function is called, it does not enter the function. Similar to step over in VC and other tools. You can add count or not. If you do not add count, it means to execute the count command next to it, and then stop.
Set step-mode
Set step-mode on
When the step-mode is enabled, the program does not stop without the debug information during the single-step tracking. This parameter is helpful for viewing the machine code.
Set step-mod off
Disable step-mode.
Finish
Run the program until the current function is complete. The stack address, return value, and parameter value returned by the function are printed.
Until or u
When you get tired of one-step tracking in a loop body, this command can run the program until you exit the loop body.
Stepi or si
Nexti or ni
Track One machine command in one step! A program code may be executed by several machine commands. stepi and nexti can execute machine commands in one step. The command with the same functions is "display/I $ pc". After running this command, A single-step trace will execute machine commands (that is, compile code) while executing program code)
9. Signal)
A signal is a soft interrupt and a method for processing asynchronous events. Generally, the operating system supports many signals. Especially UNIX,
Important applications generally process signals. UNIX defines many signals. For example, SIGINT indicates the interrupt character signal, that is, the Ctrl + C signal,
SIGBUS indicates the signal of hardware failure; SIGCHLD indicates the signal of sub-process status change; SIGKILL indicates the signal of terminating the program running, and so on.
Semaphore programming is a very important technology in UNIX.
GDB can process any signal when you debug the program. You can tell GDB which signal to process.
You can ask GDB to immediately stop the running program when receiving the signal you specified for debugging.
You can use the GDB handle command to complete this function.
Handle
Define a signal processing in GDB. Signal It can start with or not with SIG and define a range of signals to process (for example, a SIGIO-SIGKILL that represents signals from SIGIO to SIGKILL, including SIGIO, SIGIOT, or use the keyword "all" to indicate all signals to be processed. Once the debugged program receives a signal, the running program will be immediately stopped by GDB for debugging. Its <keywords> can be one or more of the following keywords.
Nostop
When the program to be debugged receives a signal, GDB will not stop the program running, but will send a message to tell you to receive this signal.
Stop
When the program to be debugged receives a signal, GDB stops your program.
Print
When the program to be debugged receives a signal, GDB displays a message.
Noprint
When the program to be debugged receives a signal, GDB will not tell you the signal information.
Pass
Noignore
When the program to be debugged receives a signal, GDB does not process the signal. This indicates that GDB will hand over the signal to the debugged program for processing.
Nopass
Ignore
When the program to be debugged receives a signal, GDB will not let the program to be debugged process the signal.
Info signals
Info handle
Check which signals are being detected by GDB.
10. Thread Stops)
If your program is multi-threaded, you can define whether your breakpoint is on all threads or on a specific thread. GDB can easily help you complete this task.
Break Thread
Break Thread If...
Linespec specifies the line number of the source program where the breakpoint is set. Threadno specifies the thread ID. Note that this ID is allocated by GDB. You can run the "info threads" command to view the thread information in the running program. If you do not specify the thread It indicates that your breakpoint is set on all threads. You can also specify breakpoint conditions for a thread. For example:
(Gdb) break frik. c: 13 thread 28 if bartab> lim
When your program is stopped by GDB, all running threads are stopped. This allows you to view the overall situation of the running program.
When you resume the program running, all threads will be resumed. Even when the main process is being debugged in a single step.
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