ksaitoの日記

日々試したことの覚え書き

gdb

移転しました。

自動的にリダイレクトします。

gdbを使ってみました。
なんだか、なつかしい操作感です。

インストール

$ sudo aptitude install gdb

サンプルソースの準備

gdbを使うためのサンプルソースを準備します。

$ cat sample.c
#include <stdio.h>

main(int argc, char* argv[])
{
  int i;
  for (i=0; i < 10; i++) {
    printf("Hello, World!!\n");
  }
}
$ CC=gcc CFLAGS=-g make sample
gcc -g    sample.c   -o sample
$ 

gdbの起動と終了

起動は、gdbの引数に実行するコマンドを指定するだけです。
(gdb)というプロンプトが表示されるので、listでソースを表示、runで実行、quitで終了できます。

$ gdb sample
GNU gdb (GDB) 7.1-ubuntu
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-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from ~/src/gdb/sample...done.
(gdb) list
1	#include <stdio.h>
2	
3	main(int argc, char* argv[])
4	{
5	  int i;
6	  for (i=0; i < 10; i++) {
7	    printf("Hello, World!!\n");
8	  }
9	}
(gdb) r
Starting program: ~/src/gdb/sample 
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!

Program exited with code 017.
(gdb) q
$ 

ブレークポイントの設定

bに続いて行番号や関数名でブレークポイントが設定できます。
info bで設定済のブレークポイントが一覧できます。

(gdb) ist
Undefined command: "ist".  Try "help".
(gdb) list
1	#include <stdio.h>
2	
3	main(int argc, char* argv[])
4	{
5	  int i;
6	  for (i=0; i < 10; i++) {
7	    printf("Hello, World!!\n");
8	  }
9	}
(gdb) b 7
Breakpoint 1 at 0x40053c: file sample.c, line 7.

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x000000000040053c in main at sample.c:7
(gdb)

変数を表示する

ブレークポイントで停止させたらpコマンドで変数を表示できます。

(gdb) r
Starting program: ~/src/gdb/sample 

Breakpoint 1, main (argc=1, argv=0x7fffffffe778) at sample.c:7
7	    printf("Hello, World!!\n");
(gdb) p i
$1 = 0
(gdb)

watchコマンドで変数を監視できます。

(gdb) wa i
Hardware watchpoint 2: i
(gdb) c
Continuing.
Hello, World!!
Hardware watchpoint 2: i

Old value = 1
New value = 2
0x000000000040054a in main (argc=1, argv=0x7fffffffe778) at sample.c:6
6	  for (i=0; i < 10; i++) {
(gdb)