162Chapter5 • Working with GNU Debugger
Now let us compile the program using the –
O2
option for optimization. The command line
for this is shown below:
gcc –O2 -g sumopt.c -o sumopt
Now let us trace through the optimized program. The
gdb
session for this purpose is listed
below:
[rr@conformix 5]$ gdb sumopt
GNU gdb 5.0rh-5 Red Hat Linux 7.1
Copyright 2001 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-redhat-linux"...
(gdb) break main
Breakpoint 1 at 0x8048466: file sumopt.c, line 10.
(gdb) run
Starting program: /home/rr/5/sumopt
Breakpoint 1, main () at sumopt.c:10
10 printf("\nThe sum is : %d\n", total);
(gdb) n
The sum is : 10
11 }
(gdb) n
Program exited with code 021.
(gdb)
This is quite different from what you may have expected. The first difference is in setting
up the break point. We used the same command to set up the break point but now
gdb
set it up at
line number 10 instead of line number 6 as it had done before. When we started execution of the
program, it jumped to line number 10 and did not go to any line before that. This is because
when we optimized code at the compile time, the compiler was smart enough to know that all
values are static so there is no need to assign two static numbers to variables at the run time and
then calculate their sum. All this can be done at the compile time, which results in shorter code
and better execution time.
The bottom line is that if you find that
gdb
is not executing some lines when you debug
a program, it may be due to the optimization level used when compiling a program. A fun
trick might be to look at the variable values during such a debug session as well, but it’s not
necessary!
Next Page >>
<< Previous Page
Back to the Table of Contents