Compiling C and C
Compiling C and C
gcc is the "GNU" C Compiler, and g++ is the "GNU C++ compiler, while cc and CC are the Sun C and C++ compilers also available on Sun workstations. Below are several examples that show how to use g++ to compile C++ programs, although much of the information applies to C programs as well as compiling with the other compilers.
This command compiles hello.C into an executable program named "hello" that you run by typing 'hello' at the command line. It does nothing more than print the word "hello" on the screen. Alternatively, the above program could be compiled using the following two commands.
g++ -c hello.C g++ hello.o -o hello
The end result is the same, but this two-step method first compiles hello.C into a machine code file named "hello.o" and then links hello.o with some system libraries to produce the final program "hello". In fact the first method also does this two-stage process of compiling and linking, but the stages are done transparently, and the intermediate file "hello.o" is deleted in the process.
Have the compiler generate many warnings about syntactically correct but questionable looking code. It is good practice to always use this option with gcc and g++.
g++ -Wall myprog.C -o myprog
Generate optimized code on a Solaris machine with warnings. The -O is a capital o and not the number 0!
g++ -Wall -O -mv8 myprog.C -o myprog
Generate optimized code on a Solaris machine using Sun's own CC compiler. This code will generally be faster than g++ optimized code.
CC -fast myprog.C -o myprog
If "myprog.c" is a C program, then the above commands will all work by replacing g++ with gcc and "myprog.C" with "myprog.c". Below are a few examples that apply only to C programs. Compile a C program that uses math functions such as "sqrt".
gcc myprog.C -o myprog -lm
Compile a C program with the "electric fence" library. This library, available on all the Linux machines, causes many incorrectly written programs to crash as soon as an error occurs. It is useful for debugging as the error location can be quickly determined using gdb. However, it should only be used for debugging as the executable myprog will be much slower and use much more memory than usual.
gcc -g myprog.C -o myprog -lefence
The same result can be achieved using the following three commands:
g++ -c file1.C g++ -c file2.C g++ file1.o file2.o -o myprog
The advantage of the second method is that it compiles each of the source files separately. If, for instance, the above commands were used to create "myprog", and "file1.C" was subsequently modified, then the following commands would correctly update "myprog".
g++ -c file1.C g++ file1.o file2.o -o myprog
Note that file2.C does not need to be recompiled, so the time required to rebuild myprog is shorter than if the first method for compiling myprog were used. When there are numerous source file, and a change is only made to one of them, the time savings can be significant. This process, though somewhat complicated, is generally handled automatically by a makefile. </body>
# GDB Command Line Arguments # GDB Commands # Dereferencing STL Containers # GDB Man Pages # Links # Books
search
Search
Related YoLinux Tutorials: C++ Info, links C++ String Class C++ STL vector, list Emacs and C/C++ Advanced VI CGI in C++ Clearcase Commands MS/Visual C++
Command line options: (version 6. Older versions use a single "-") Option --help -h --exec=file-name -e file-name Description List command line arguments Identify executable associated with core file.
--core=name-of-corefile -c name-of-core-file
-File listing GDB commands to command=command- perform. Good for automating setfile up. -x command-file --directory=directory -d directory --cd=directory Add directory to the path to search for source files. Run GDB using specified directory as the current working directory. Do not execute commands from ~/.gdbinit initialization file. Default is to look at this file and execute the list of commands. Run in batch (not interactive) mode. Execute commands from file. Requires -x option. Read symbol table from file file. Enable writing into executable and core files. Do not print the introductory and copyright messages. Specify device for running program's standard input and output. Specify process ID number to attach to.
--nx -n
--batch -x commandfile --symbols=file-name -s file-name --write --quiet -q Free Information Technology Software and Development Magazine Subscriptions and Document Downloads --tty=device
GDB Commands:
Commands used within GDB: Command help help topic-classes help command apropos search-word Description List gdb command topics. List gdb command within class. Command description. Search for commands and
command topics containing search-word. info args i args info breakpoints info break info break breakpointnumber info watchpoints info registers info threads info set Break and Watch break funtion-name break line-number
break ClassName::functionNam e
List program command line arguments List breakpoints List breakpoint numbers. List info about specific breakpoint. List breakpoints List registers in use List threads in use List set-able option Suspend program at specified function of line number.
Set a breakpoint specified number of lines forward or back from the position at which execution stopped. Don't specify path, just the file name and function name. Don't specify path, just the file name and line number.
break Directory/Path/filename.cpp:6 2
break *address
Suspend processing at an instruction address. Used when you do not have source. Where condition is an expression. i.e. x > 5 Suspend when boolean expression is true.
break line thread thread- Break in thread at specified line number number. Use info threads to display thread numbers. tbreak Temporary break. Break once only. Break is then removed. See
"break" above for options. watch condition clear clear function clear line-number delete d delete breakpointnumber delete range disable breakpointnumber-or-range enable breakpointnumber-or-range enable breakpointnumber once continue c continue number Suspend processing when condition is met. i.e. x > 5 Delete breakpoints as identified by command option. Delete all breakpoints, watchpoints, or catchpoints. Delete the breakpoints, watchpoints, or catchpoints of the breakpoint ranges specified as arguments. Does not delete breakpoints. Just enables/disables them. Example: Show breakpoints: info break Disable: disable 2-9 Enables once Continue executing until next break point/watchpoint. Continue but ignore current breakpoint number times. Usefull for breakpoints within a loop. Continue to end of function.
step Step to next line of code. Will s step into a function. step number-of-steps-toperform next n next number until until line-number Execute next line of code. Will not enter functions. Continue processing until you reacha aspecified line number. Also: function name, address, filename:function or filename:line-number. step/next assembly/processor instruction.
stepi si nexti
ni info signals info handle handle SIGNAL-NAME option where Stack backtrace Show trace of where you are bt currently. Which functions you bt inner-function-nesting- are in. Prints stack backtrace. depth bt -outer-functionnesting-depth backtrace full frame number f number up number down number info frame Print values of local variables. Select frame number. Move up/down the specified number of frames in the stack. List address, language, address of arguments/local variables and which registers were saved in frame. Info arguments of selected frame, local variables and exception handlers. List source code. Perform the following option when signal recieved: nostop, stop, print, noprint, pass/noignore or nopass/ignore Shows current line number and which function you are in.
info args info locals info catch Source Code list l list line-number list function list list start#,end# list filename:function set listsize count show listsize
directory directory-name Add specified directory to front of dir directory-name source code path. show directories directory Clear sourcepath when nothing specified.
Examine Variables print variable-name p variable-name p file-name::variablename p 'file-name'::variablename Print value stored in variable.
p *array-variable@length Print first # values of array specified by length. Good for pointers to dynamicaly allocated memory. p/x variable p/d variable p/u variable p/o variable p/t variable x/b address x/b &variable p/c variable p/f variable p/a variable x/w address x/4b &variable GDB Modes set gdb-option value set logging on set logging off show logging set logging file log-file set print array on set print array off show print array Set a GDB option Turn on/off logging. Default name of file is gdb.txt Print as integer variable in hex. Print variable as a signed integer. Print variable as a un-signed integer. Print variable as a octal. Print as integer value in binary. (1 byte/8bits) Print integer as character. Print variable as floating point number. Print as a hex address. Print binary representation of 4 bytes (1 32 bit word) of memory pointed to by address.
set print array-indexes on Default off. Print index of array set print array-indexes off elements. show print array-indexes set print pretty on Format printing of C structures.
set print pretty off show print pretty set print union on set print union off show print union set print demangle on set print demangle off show print demangle Start and Stop run r run command-linearguments run < infile > outfile continue c kill quit q Start program execution from the beginning of the program. The command break main will get you started. Also allows basic I/O redirection. Continue execution to next break point. Stop program execution. Exit GDB debugger. Default is on. Print C unions.
GDB Operation:
Compile with the "-g" option (for most GNU and Intel compilers) which generates added information in the object code so the debugger can match a line of source code with the step of execution. Do not use compiler optimization directive such as "-O" or "O2" which rearrange computing operations to gain speed as this reordering will not match the order of execution in the source code and it may be impossible to follow. control+c: Stop execution. It can stop program anywhere, in your source or a C library or anywhere. To execute a shell command: ! command or shell command GDB command completion: Use TAB key info bre + TAB will complete the command resulting in info
breakpoints
Press TAB twice to see all available options if more than one option is available or type "M-?" + RETURN. GDB command abreviation: info bre + RETURN will work as bre is a valid abreviation for breakpoints
De-Referencing a vector:
Example: STL_vector_int.cpp view source
print?
01 #include <iostream> 02 #include <vector>
03 #include <string> 04
07 main() 08 {
09 vector<int> II; 10
11 II.push_back(10); 12 II.push_back(20);
13 II.push_back(30); 14
17 }
6 7 main() 8 { 9 vector<int> II; 10 (gdb) l 11 II.push_back(10); 12 II.push_back(20); 13 II.push_back(30); 14 15 cout << II.size() << endl; 16 17 } (gdb) break 15 Breakpoint 1 at 0x8048848: file STL_vector_int.cpp, line 15. (gdb) r Starting program: /home/userx/a.out Breakpoint 1, main () at STL_vector_int.cpp:15 15 cout << II.size() << endl; (gdb) p II $1 = { <std::_Vector_base<int,std::allocator<int> >> = { _M_impl = { <std::allocator<int>> = { <__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, members of std::_Vector_base<int,std::allocator<int> >::_Vector_impl: _M_start = 0x804b028, _M_finish = 0x804b034, _M_end_of_storage = 0x804b038 } }, <No data fields>} (gdb) pvector II elem[0]: $2 = 10 elem[1]: $3 = 20 elem[2]: $4 = 30 Vector size = 3 Vector capacity = 4 Element type = int * (gdb) c Continuing. 3 Program exited normally. (gdb) quit
Notice the native GDB print "p" results in an cryptic display while the "pvector" routine from the GDB script provided a human decipherable display of your data.
05 06 main()
09 10 vI2Matrix[0][0] = 0;
15 vI2Matrix[2][1] = 21; 16
25 } 26 }
27 }
elem[0]: $1 = { <std::_Vector_base<int,std::allocator<int> >> = { _M_impl = { <std::allocator<int>> = { <__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, members of std::_Vector_base<int,std::allocator<int> >::_Vector_impl: _M_start = 0x804b040, _M_finish = 0x804b048, _M_end_of_storage = 0x804b048 } }, <No data fields>} elem[1]: $2 = { <std::_Vector_base<int,std::allocator<int> >> = { _M_impl = { <std::allocator<int>> = { <__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, members of std::_Vector_base<int,std::allocator<int> >::_Vector_impl: _M_start = 0x804b050, _M_finish = 0x804b058, _M_end_of_storage = 0x804b058 } }, <No data fields>} elem[2]: $3 = { <std::_Vector_base<int,std::allocator<int> >> = { _M_impl = { <std::allocator<int>> = { <__gnu_cxx::new_allocator<int>> = {<No data fields>}, <No data fields>}, members of std::_Vector_base<int,std::allocator<int> >::_Vector_impl: _M_start = 0x804b060, _M_finish = 0x804b068, _M_end_of_storage = 0x804b068 ---Type <return> to continue, or q <return> to quit--} }, <No data fields>} Vector size = 3 Vector capacity = 3 Element type = class std::vector<int,std::allocator<int> > * (gdb) pvector $1 elem[0]: $4 = 0 elem[1]: $5 = 1 Vector size = 2 Vector capacity = 2 Element type = int * (gdb) pvector $2 elem[0]: $6 = 10 elem[1]: $7 = 11 Vector size = 2 Vector capacity = 2
Element type = int * (gdb) pvector $3 elem[0]: $8 = 20 elem[1]: $9 = 21 Vector size = 2 Vector capacity = 2 Element type = int * (gdb) p vI2Matrix $10 = { <std::_Vector_base<std::vector<int, std::allocator<int> >,std::allocator<std::vector<int, std::allocator<int> > > >> = { _M_impl = { <std::allocator<std::vector<int, std::allocator<int> > >> = { <__gnu_cxx::new_allocator<std::vector<int, std::allocator<int> > >> = {<No data fields>}, <No data fields>}, members of std::_Vector_base<std::vector<int, std::allocator<int> >,std::allocator<std::vector<int, std::allocator<int> > > >::_Vector_impl: _M_start = 0x804b018, _M_finish = 0x804b03c, _M_end_of_storage = 0x804b03c } }, <No data fields>} (gdb) quit
Note "pvector" does not de-reference the entire vector of vectors all at once but returns vectors $1, $2 and $3. The "pvector" command then helps us traverse the information by examining the contents of each element in the individual "terminal" vectors. Note that the native gdb "p vI2Matrix" (last command) was much less informative.
Man Pages:
gdb - GNU debugger ld - Linker gcc/g++ - GNU project C and C++ compiler
Links:
Books:
"Debugging with GDB: The GNU Source-Level Debugger" by Richard Stallman, Roland H. Pesch, Stan Shebs ISBN # 1882114884, Free Software Foundation; 9th edition (January 1, 2002) "GDB Pocket Reference" by Arnold Robbins ISBN # 0596100272, O'Reilly
"Advanced Linux Programming" by Mark Mitchell, Jeffrey Oldham, Alex Samuel, Jeffery Oldham ISBN # 0735710430, New Riders Good book for programmers who already know how to program and just need to know the Linux specifics. Covers a variety of Linux tools, libraries, API's and techniques. If you don't know how to program, start with a book on C.
Summary: Most flavours of Linux come with the GNU debugger, or gdb to the shell. Gdb lets you see the internal structure of a program, print out variable values, set breakpoints and single step through source code. It makes an extremely powerful tool for fixing problems in program code. In this article I'll try to show how cool and useful gdb is.
Tag this! Update My dW interests (Log in | What's this?) Skip to help for Update My dW interests
Compiling Before you can get started, the program you want to debug has to be compiled with debugging information in it. This is so gdb can work out the variables, lines and functions being used. To do this, compile your program under gcc (or g++) with an extra '-g' option: gcc -g eg.c -o eg
Back to top Running gdb Gdb is run from the shell with the command 'gdb' with the program name as a parameter, for example 'gdb eg', or you can use the file command once inside gdb to load a program for debugging, for example 'file eg'. Both of these assume you execute the commands from the same directory as the program. Once loaded, the program can be started with the gdb command 'run'.
Back to top An example debugging session If nothing is wrong your program will execute to completion, at which point gdb will get control back. But what if something does go wrong? In this case gdb will take control and interrupt the program, allowing you to examine the state of everything and hopefully find out why. To provoke this scenario we'll use an example program:
#include int wib(int no1, int no2) { int result, diff; diff = no1 - no2; result = no1 / diff; return result; } int main(int argc, char *argv[]) { int value, div, result, i, total; value = 10;
This program runs around a for loop 10 times, calculating a cumulative value using the 'wib()' function and finally printing out the result. Enter it into your favorite text editor with the same line spacings, save as 'eg1.c', compile with 'gcc -g eg1.c -o eg1' and start gdb with 'gdb eg1'. Rupning the program using 'run' will result in a message something like:
Program received signal SIGFPE, Arithmetic exception. 0x80483ea in wib (no1=8, no2=8) at eg1.c:7 7 result = no1 / diff; (gdb)
Gdb indicates that the program gets an arithmetic exception at line 7 and usefully prints out the line and the values of the arguments to the wib() function. To see the source code around line 7 use the command 'list', which usually prints 10 lines. Typing 'list' again (or pressing return which repeats the last command) will list the next 10 lines of the program. From the gdb message something is going wrong with the divide at line 7 where the program divides the variable "no1" by "diff". To see the values of variables the gdb 'print' command is used with the variable name. We can see what "no1" and "diff" are equal to by typing 'print no1' and 'print diff', resulting in:
(gdb) print no1 $5 = 8 (gdb) print diff $2 = 0
Gdb indicates that "no1" equals 8 and "diff" equals 0. From these values and line 7 we can deduce that the arithmetic exception is due to a divide by zero. The listing shows the variable "diff" being calculated on line 6, which we can re-evaluate by supplying the "diff" expression to print as 'print no1 - no2'. Gdb told us that the arguments to the wib function were both equal to 8 so we might wish to examine the main() function which calls wib() to see when this happens. In the meantime to allow our program to die naturally we tell gdb to carry on execution with the 'continue' command:
(gdb) continue Continuing. Program terminated with signal SIGFPE, Arithmetic exception. The program no longer exists.
Back to top Using breakpoints To see what's going on in main() we can set a breakpoint at a particular line or on a function in the program code so gdb will interrupt execution when it is reached. We could set a breakpoint when the main() function is entered with the command 'break main', or specify any other function name we were interested in. For our purposes however we'll break just before the wib() function is called. Typing 'list main' will print the source listing starting around the main() function and pressing return again will reveal the wib() function call is on line 21. To set a breakpoint there we type 'break 21'. Gdb will issue the response:
(gdb) break 21 Breakpoint 1 at 0x8048428: file eg1.c, line 21.
to show that it has set breakpoint 1 at the line we requested. The 'run' command will rerun the program from the beginning until gdb breaks. When this happens gdb will generate a message showing which breakpoint it broke on and where the program was:
Breakpoint 1, main (argc=1, argv=0xbffff954) at eg1.c:21 21 result = wib(value, div);
Issuing 'print value' and 'print div' will show that the variables are 10 and 6 for this first wib() call and 'print i' will show zero. Happily gdb will show the value of all local variables and save a lot of typing with the 'info locals' command. From the previous investigation the problem occurs when "value" and "div" are equal, so type 'continue' to resume execution until breakpoint 1 is next reached. For this iteration 'info locals' shows value=9 and div=7. Rather than continuing again we can single step through the program to see how "value" and "div" are being changed using the command 'next'. Gdb will respond with:
(gdb) next 22 total += result;
pressing return a couple more times will show an addition and subtraction:
(gdb) 23 (gdb) 24
div++; value--;
and another two returns will get us to line 21, ready for the wib() call. 'info locals' will show that now "div" equals "value", spelling forthcoming trouble. For interest's sake we can follow execution into the wib() function to see the divide error again by issuing the 'step' command (as opposed to 'next' which steps over function calls) followed by a 'next' to get to the "result" calculation. Now that we're finished debugging, gdb can be exited with the 'quit' command. Because the program is still running and this action will terminate it, gdb will prompt for confirmation.
Back to top More breakpoints and watchpoints In the previous example we set a breakpoint at line 21 because we were interested in when "value" equaled "div" before the wib() function was called. We had to continue program execution twice to get to this point, however by setting a condition on the breakpoint we can make gdb halt only when "value" actually equals "div". To set the condition when defining the breakpoint we can specify "break <line number> if <conditional expression>". Load eg1 into gdb again and type:
(gdb) break 21 if value==div Breakpoint 1 at 0x8048428: file eg1.c, line 21.
If a breakpoint such as number 1 was already defined at line 21 we could use the 'condition' command instead to set the condition on the breakpoint:
(gdb) condition 1 value==div
Running eg1.c with 'run' gdb will break when "value" equals "div", avoiding having to 'continue' manually until they are equal. Breakpoint conditions can be any valid C expression when debugging C programs, indeed any valid expression in the language your program is using. The variables specified in the condition must be in scope at whatever line you set the breakpoint on, otherwise the expression wouldn't make sense! Breakpoints can be set to unconditional using the 'condition' command specifying a breakpoint number without an expression, for example 'condition 1' sets breakpoint 1 to unconditional.
To see what breakpoints are currently defined and their conditions issue the command 'info break':
(gdb) info break Num Type Disp Enb Address What 1 breakpoint keep y 0x08048428 in main at eg1.c:21 stop only if value == div breakpoint already hit 1 time
Along with any conditions and how many times it's been hit, the breakpoint information specifies whether the breakpoint is enabled in the 'Enb' column. Breakpoints can be disabled using the command 'disable <breakpoint number>', enabled with 'enable <breakpoint number>' or deleted entirely with 'delete <breakpoint number>', for example 'disable 1' prevents breaking on point 1. If we were more interested in when "value" became equal to "div" we could set a different type of breakpoint called a watch. A watchpoint will break program execution when the specified expression changes value, but it must be set when the variables used in the expression are in scope. To get "value" and "div" in scope we can set a breakpoint on main and run the program, setting our watchpoints when the main() breakpoint is hit. Restart gdb with eg1 and type:
(gdb) break main Breakpoint 1 at 0x8048402: file eg1.c, line 15. (gdb) run ... Breakpoint 1, main (argc=1, argv=0xbffff954) at eg1.c:15 15 value = 10;
To keep track of when "div" changes we could use 'watch div', but as we want to break when "div" equals "value" type:
(gdb) watch div==value Hardware watchpoint 2: div == value
Continuing will result in Gdb breaking when the expression "div==value" changes value from 0 (false) to 1 (true):
(gdb) continue Continuing. Hardware watchpoint 2: div == value Old value = 0 New value = 1 main (argc=1, argv=0xbffff954) at eg1.c:19 19 for(i = 0; i < 10; i++)
An 'info locals' command will verify that "value" is indeed equal to "div" (8 again).
Defined watchpoints can be listed along with breakpoints with the 'info watch' command (the command is equivalent to 'info break') and watchpoints can be enabled, disabled and deleted using the same syntax as for breakpoints.
Back to top Core files Running programs under gdb makes for easier bug trapping, but usually a program will die outside of the debugger leaving only a core file. Gdb can load core files and let you examine the state of the program before it died. Running our example program eg1 outside of gdb will result in a core dump:
$ ./eg1 Floating point exception (core dumped)
To start gdb with a core file, issue the command 'gdb eg1 core' or 'gdb eg1 -c core' from the shell. Gdb will load up the core file, eg1's program listing, show how the program terminated and present a message very much like we've just run the program under gdb:
... Core was generated by `./eg1'. Program terminated with signal 8, Floating point exception. ... #0 0x80483ea in wib (no1=8, no2=8) at eg1.c:7 7 result = no1 / diff;
At this point we can issue 'info locals', 'print', 'info args' and 'list' to see the values which caused the divide-by-zero. The command 'info variables' will print out the values of all program variables, but will take a long time because gdb prints variables from the C library as well as our program code. In order to more easily find out what happened in the function which called wib() we can use gdb's stack commands.
Back to top Stack traces The program "call stack" is a list of functions which led up to the current one. Each function and its variables are assigned a "frame" with the most recently called function in frame 0 (the "bottom" frame). To print the stack, issue the command 'bt' (short for 'backtrace'):
(gdb) bt #0 0x80483ea in wib (no1=8, no2=8) at eg1.c:7 #1 0x8048435 in main (argc=1, argv=0xbffff9c4) at eg1.c:21
This shows that the function wib() was called from main() at line 21 (a quick 'list 21' will confirm this), that wib() is in frame 0 and main() in frame 1. Because wib() is in frame 0 that's the function the program was executing inside when the arithmetic error occurred. When you issue the 'info locals' command gdb actually prints out variables local to the current frame, which by default is where the interrupted function is (frame 0). The current frame can be printed with the command 'frame'. To see variables from the main function (which is in frame 1) we can switch to frame 1 by issuing 'frame 1' followed by 'info locals':
(gdb) frame 1 #1 0x8048435 in main (argc=1, argv=0xbffff9c4) at eg1.c:21 21 result = wib(value, div); (gdb) info locals value = 8 div = 8 result = 4 i = 2 total = 6
This shows that the error occurred on the third time through the "for" loop (i equals 2) when "value" equaled "div". Frames can be switched through either by specifying their number explicitly to the 'frame' command as above or with the command 'up' to move up the stack and 'down' to move down. To get further information about a frame such as its address and the program language you can use the command 'info frame'. Gdb stack commands work during program execution as well as on core files, so for complicated programs you can trace how the program arrives at functions while it's running.
Back to top Attaching to other processes In addition to debugging with core files or programs, gdb can attach to an already running process (who's program has debugging information compiled in) and break into it. This is done by specifying the process ID of the program you wish to attach gdb to instead of the core filename. Here's an example program which goes round in a loop and sleeps:
#include
int main(int argc, char *argv[]) { int i; for(i = 0; i < 60; i++) { sleep(1); } return 0; }
Compile this with 'gcc -g eg2.c -o eg2' and run it with './eg2 &'. Take note of the process ID which is printed when it starts in the background, in this case 1283:
./eg2 & [3] 1283
Start gdb and specify your pid, in my case with 'gdb eg2 1283'. Gdb will look for a core file called "1283" and when it doesn't find it will attach and break into to process 1283, wherever it's running (in this case probably in sleep()):
... /home/seager/gdb/1283: No such file or directory. Attaching to program: /home/seager/gdb/eg2, Pid 1283 ... 0x400a87f1 in __libc_nanosleep () from /lib/libc.so.6 (gdb)
At this point all the usual gdb commands can be issued. We can use 'backtrace' to see where we are in relation to main() and what main()'s frame number is, then switch frames there and find out how many times we've been through the "for" loop:
(gdb) backtrace #0 0x400a87f1 in __libc_nanosleep () from /lib/libc.so.6 #1 0x400a877d in __sleep (seconds=1) at ../sysdeps/unix/sysv/linux/sleep.c:78 #2 0x80483ef in main (argc=1, argv=0xbffff9c4) at eg2.c:7 (gdb) frame 2 #2 0x80483ef in main (argc=1, argv=0xbffff9c4) at eg2.c:7 7 sleep(1); (gdb) print i $1 = 50
When we're done with the program we can leave it to carry on executing with the 'detach' command or kill it with the 'kill' command. We could also attach to eg2 under pid 1283 by first loading the file in with 'file eg2' then issuing the attach command 'attach 1283'.
Back to top Other neat tricks Gdb allows you to run shell commands without exiting the debugging environment with the shell command, invoked as 'shell [commandline]', useful for making changes to source code whilst debugging. Finally you can modify the values of variables whilst a program is running using the 'set ' command. Run eg1 again under gdb, set a conditional breakpoint at line 7 (where result is calculated) with the command 'break 7 if diff==0' and run the program. When gdb interrupts execution "diff" can be set to a non-zero value to get the program to run to completion:
Breakpoint 1, wib (no1=8, no2=8) at eg1.c:7 7 result = no1 / diff; (gdb) print diff $1 = 0 (gdb) set diff=1 (gdb) continue Continuing. 0 wibed by 16 equals 10 Program exited normally.
Back to top Conclusion The GNU Debugger is a very powerful tool in any programmer's arsenal. I've only covered a small subset of what it can do here, to find out more I'd encourage you to have a read of the GNU Debugger manual pages.
Resources
GNU Debugger manual Source code for the example debugging session. Source code for the attach example.
David Seager, a software developer with IBM, has been playing with Linux and Web-based applications for over 2 years. Close [x]
Report abuse help
Report abuse
Thank you. This entry has been flagged for moderator attention.
Close [x]
Report abuse help
Report abuse
Report abuse submission failed. Please try again later.
Close [x]
developerWorks: Sign in
If you don't have an IBM ID and password, register here. IBM ID: Forgot your IBM ID? Password: Forgot your password? Change your password After sign in:
Stay on the current page
The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post. All information submitted is secure. Close [x]
Comments Add comment: Sign in or register to leave a comment. Note: HTML elements are not supported within comments.
Total comments (2) Nicely explained tutorial. Hard to find such concise tutorials that conveys idea. Posted by parthan on 22 October 2010 Report abuse Thanks for the great tutorial! Posted by Nikhil_Jindal on 01 July 2010 Report abuse
What's this?
This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks. And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you. View your My developerWorks profile Return from help Close [x]
Help: Remove from My dW interests
What's this?
Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content. View your My developerWorks profile Return from help
Table of contents
More breakpoints and watchpoints Core files Stack traces Attaching to other processes Other neat tricks Conclusion Resources About the author Comments
Local resources
IBM Innovation Center - India: Bangalore developerWorks Resources India Technical Briefings in Asia
Tags
Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).
Popular article tags | My article tagsSkip to tags list Popular article tags | My article tags
Skip to tags list
Popular tags
android (69) apache (47) api (32) application_a... (81) application_... (402) architecture (257) architecture_-... (43) atom (39) business_proce... (39) business_proce... (47) cloud (110) cloud_computi... (84) components (47) configuration_... (48) css_(cascading... (35) databases_and... (121) db2 (32) design (43) development (34) dojo (45) dom_(document_... (38) eclipse (115) editing (37) formatting (35) frameworks (46) general_progr... (104) google (33) html (84) html5 (67) integration (49) interoperabili... (45) java (327) java_technol... (186) javascript (137) jquery (51) jsf (33) json (35) json_(javascri... (35) linux (281) mashups (39) messaging (64) mobile (36) multimedia (35) namespaces (37) open_source (248) parsing (42) patterns (36) performance (74)
perl (35) php (126) php_(hypertex... (108) programming (39) python (80) rest (63) rss_(really_si... (33) schemas (68) security (78) services (51) soa (116) soa_(service-... (147) soap_(simple_... (89) spring (37) standards (95) standards_and... (56) tips (46) web (121) web_2.0 (125) web_authoring (59) web_developme... (58) web_services (268) websphere (56) wsdl_(web_serv... (43) xhtml_(extensi... (41) xml (390) xpath_(xml_pat... (51) xquery_(xml_qu... (46) xslt (43) xslt_(xsl_tran... (52)
My tags
To access My Tags, please sign in
ajax (209)
and (46) android (69) apache (47) api (32) application_a... (81) application_... (402) architecture (257) architecture_-... (43) atom (39) business_proce... (39) business_proce... (47) cloud (110) cloud_computi... (84) components (47) configuration_... (48) css_(cascading... (35) databases_and... (121) db2 (32) design (43) development (34) dojo (45) dom_(document_... (38) eclipse (115) editing (37) formatting (35) frameworks (46) general_progr... (104) google (33) html (84) html5 (67) integration (49) interoperabili... (45) java (327) java_technol... (186) javascript (137) jquery (51) jsf (33) json (35) json_(javascri... (35) linux (281) mashups (39) messaging (64) mobile (36) multimedia (35) namespaces (37) open_source (248) parsing (42) patterns (36)
performance (74) perl (35) php (126) php_(hypertex... (108) programming (39) python (80) rest (63) rss_(really_si... (33) schemas (68) security (78) services (51) soa (116) soa_(service-... (147) soap_(simple_... (89) spring (37) standards (95) standards_and... (56) tips (46) web (121) web_2.0 (125) web_authoring (59) web_developme... (58) web_services (268) websphere (56) wsdl_(web_serv... (43) xhtml_(extensi... (41) xml (390) xpath_(xml_pat... (51) xquery_(xml_qu... (46) xslt (43) xslt_(xsl_tran... (52)
ajax 209 and 46 android 69 apache 47 api 32 application_a... 81 application_d... 402 architecture 257 architecture_... 43 atom 39
Overview New to Linux Open source projects Technical library (articles, tutorials, training, and more) Forums Events Newsletter
Seeking nominations
Nominate IBM Champions: experts who help you build a smarter planet with IBM
Special offers
Technical topics
AIX and UNIX IBM i Information Management Lotus Rational Tivoli WebSphere Cloud computing Industries Integrated Service Management Java technology Linux Open source SOA and web services Web development XML
Events
Briefings Webcasts Find events
Community
Forums Groups Blogs Wikis Terms of use Report abuse IBM Champion program
Related resources
Students and faculty Business Partners
IBM
Solutions Software Software services Support Product information Redbooks Privacy Accessibility
return result; } int main(int argc, char *argv[]) { int value, div, result, i, total; value = 10; div = 6; total = 0; for(i = 0; i < 10; i++) { result = wib(value, div); total += result; div++; value--; } printf("%d wibed by %d equals %d\n", value, div, total); return 0; }