Sunday, September 20, 2015

C++: Looking at source code while debugging in GDB

Sometimes when I am debugging my code for issues/bugs, I want to look at the surrounding piece of code where my debugger is executing, or may be I want to look at the some lines of code in a particular file. Its quite time consuming to toggle windows, switch source code editor/IDE locating code(sometimes switch desktops). Worry no more, use the following commands, to help you navigate through the code, while debugging.

Scenario: after you have set your breakpoint and the GDB debugger hits the section, and you want to look around those line, type list

[Parag@paragpc:/home/Parag/Workspace/Utils]gdb sample
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/Parag/Workspace/Utils/sample...done.
(gdb) break countLines
Breakpoint 1 at 0x400cf2: file MultiUseHeader.hpp, line 21.
(gdb) run
Starting program: /home/sid/Parag/Workspace/Utils/samp 
inside registerQuickExitHandlers()

Breakpoint 1, countLines () at MultiUseHeader.hpp:21
warning: Source file is more recent than executable.
21     std::ifstream myfile(strFileName);
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6.x86_64 libgcc-4.4.7-11.el6.x86_64 libstdc++-4.4.7-11.el6.x86_64
(gdb) list
16  char cArr[2];
17 };
18 
19 int countLines(std::string& strFileName) {
20 
21     std::ifstream myfile(strFileName);
22 
23     // new lines will be skipped unless we stop it from happening:    
24     myfile.unsetf(std::ios_base::skipws);
25 
(gdb) n
24     myfile.unsetf(std::ios_base::skipws);
(gdb) n
30         '\n');
(gdb) list
25 
26     // count the newlines with an algorithm specialized for counting:
27     unsigned line_count = std::count(
28         std::istream_iterator<char>(myfile),
29         std::istream_iterator<char>(), 
30         '\n');
31 
32     std::cout << "Lines: " << line_count << "\n";
33     return 0;
34 }
(gdb) 


Similarly if you want to look at some specific lines in a source file, type:

(gdb) list MultiUseHeader.hpp:32
27     unsigned line_count = std::count(
28         std::istream_iterator<char>(myfile),
29         std::istream_iterator<char>(), 
30         '\n');
31 
32     std::cout << "Lines: " << line_count << "\n";
33     return 0;
34 }
35 
36 
(gdb) 

Section 80C TMT 2023(PA) – Standard Deduction amounting to a maximum of Rs 8670 under IT rule

With the recently concluded Tax filing season (which if I may draw parallel to the Christmas holiday season enjoyed by one and all), Indians...