首页 > IDE, 中级 > 在Emacs中使用gdb调试程序

在Emacs中使用gdb调试程序

2010年3月29日 ahei 发表评论 阅读评论

作者: Tiger Soldier

1 引言

Emacs除了具有强大的编辑功能,还可以作为调试工具gdb的前端,对程序进行调试。使用Emacs进行调试,可以将程序的编写与调试统一到Emacs中,并利用Emacs强大的功能辅助调试,是将Emacs作为IDE使用的一项必备功能。

本文假定读者具有基本的程序调试知识,希望知道在Emacs下进行基本调试的对应操作。水平有限,欢迎拍砖。

2 准备工作:将调试信息编译在程序中

要使程序能被gdb调试,需要在编译时加入调试所需的信息。如果使用gcc/g++进行编译,需要使用参数-g,如:

gcc prog.c -g -o prog

如果使用 ./confiugre && make 的编译流程,可以将使用如下方式引入-g参数:

1
2
CFLAGS="-g" ./configure
make

注意:不要加入任何优化参数(例如-O、-O2),不然调试时会有很灵异的现象发生……

3 开始:开启Emacs的调试模式GUD

3.1 运行gdb

在编译好程序后,就可以开始调试了。直接运行gdb命令M-x gdb RET 在minibuffer中会出现需要执行的gdb命令。例如:gdb –annotate=3 prog 如果当前目录下有可执行文件(通常恰好是需要调试的文件),gdb会在其后自动补上可执行文件,否则需要在minibuffer中补上要调试的程序文件名。

继续回车,Emacs的GUD(Grand Unified Debugger)就会关联到gdb并加载要调试的程序了。

3.2 gdb界面

启动gdb后,Emacs的界面会变成下面两种之一:

GDB单窗格模式

GDB多窗格模式

可以通过gdb-many-windows来切换这两种界面布局。

如果界面被打乱了(例如,在minibuffer中使用补全,查看帮助,重新编译程序),可以使用gdb-restore-windows来恢复界面布局。

3.3 小结

命令 功能
gdb 启动gdb进行调试
gdb-many-windows 切换单窗格/多窗格模式
gdb-restore-windows 恢复窗格布局

接下来就要开始调试程序了。

4 调试:设置断点,控制程序流程

4.1 设置、删除断点

首先将断点设置在要调试的地方。有两种方法:

第一种,在要设置断点的行左边的fringe上单击一下(就是文本左边与滚动条之间空出的那一块)。隐藏了fringe的朋友可以M-x fringe-mode显示它。

第二种,使用默认快捷键C-x C-a C-b, 或者 C-x <SPC>。它们都关联到命令gud-break。

无论使用哪种方法,fringe上都会在设置了断点的行上显示一个红点,表示这行设了断点:

同时,在断点buffer中也会显示已有的断点信息:

断点buffer

要删除断点,同样有两种对应的方法:在fringe的断点上单击一下,或者使用快捷键C-x C-a C-d(对应命令gud-remove)。

可以在断点buffer上单击某个断点切换到断点所在位置。将光标移动到断点处回车也有同样的效果。

在断点buffer上按空格键可以切换断点的激活和禁用状态。

4.2 运行程序

设置好断点后就可以运行程序了。单击工具栏上的运行就开始运行了。也可以使用gud-go命令来运行。奇怪的是没有任何默认快捷键绑定。

当程序运行到断点时,程序会在断点处停下来,并自动打开停下的语句所在的代码文件。同时在fringe上在停下的语句处有三角形的指示器。

现在,我们来一步步运行程序。

4.3 单步执行、运行到光标处

在调试中最常用的功能就是单步执行了。单步执行有两种:将函数调用作为一条语句执行(Next)和遇到函数时进入函数中进行调试(Step)。

要使用第一种方式,默认快捷键是C-x C-a C-n,对应命令为gud-next。也可以单击工具栏上的 单步运行跳过函数

第二种方式的默认快捷键是C-x C-a C-s,对应命令为gud-step。也可以单击工具栏上的 单步运行进入函数

如果想跳出当前函数,可以使用命令gud-finish,默认快捷键为C-x C-a C-f,工具栏上有 跳出函数 可用。

在Emacs中还可以运行到光标所在的行。使用命令gud-until即可,默认快捷键为C-x C-a C-u。1

也可以直接把当前语句指示器拖到任意一行,程序会运行到那一行再停下来。

4.4 继续运行程序

在程序中断后要继续运行程序,依然是使用gud-go命令或 继续运行 ,也可以使用命令gud-cont,对应快捷键为C-x C-a C-r。

4.5 小结

功能 命令 默认快捷键
添加断点 gud-break C-x C-a C-b 或 C-x <SPC>
删除断点 gud-remove C-x C-a C-d
运行/继续程序 gud-go
单步执行,无视函数 gud-next C-x C-a C-n
单步执行,进入函数 gud-step C-x C-a C-s
跳出当前函数 gud-finish C-x C-a C-f
运行到光标所在语句 gud-until C-x C-a C-u
继续运行程序 gud-cont C-x C-a C-r

5 察看变量的值

调试的过程中免不了要查看变更的值。Emacs提供了方便地功能让我们查看变量的值。

5.1 本地变量buffer

如果打开了gdb-many-windows,在右上角会显示Locals buffer,其中显示了当前局部变量的值。如果显示的是寄存器(Register)buffer,单击左边的Locals就可以切换到Locals buffer了。在其中可以方便地观察到各变量的值。

如果没有打开gdb-many-windows,也可以使用gdb-display-locals-buffer来显示该buffer。

5.2 察看变量值

遇到一些Locals里没有显示的变量,或者比较复杂的结构,就需要用到观察变量的功能了。

将光标停留在要观察的变量上,执行命令gud-watch,可以将变量加入观察列表中。默认的快捷键是C-x C-a C-w。也可以使用工具栏上的 查看变量

被观察的变量将在Speedbar中显示。对于复杂结构,可以单击Speedbar上的+号将其展开或收缩。在+号上按空格键也有相同的效果。2

有时候Emacs观察的变量不是你所想要的,一般是a->b这类的情况。这时可以将要观察的部分选中,再使用上述方法即可。

5.3 用工具提示显示变量值

可以用gud-tooltip-mode开启或关闭工具提示。开启后将鼠标指针停留在变量名上时将在工具提示中显示变量的值。

5.4 小结

功能 命令 默认快捷键
观察变量 gud-watch C-x C-a C-w
展开/收缩变量 <SPC>
开启/关闭工具提示 gud-tooltip-mode

6 输入输出

如果程序需要与标准输入/输出交互,那么你很可能需要用到下面要介绍的功能。

6.1 单独的IO buffer

默认来说,程序的输入输出是在gdb buffer里显示的。这样输出信息和gdb信息混合在一起,阅读起来非常不便。这时候,你需要把输入输出单独显示在一个buffer里,方便查看。

使用gdb-use-separate-io-buffer,可以在程序代码buffer右侧新建一个IO buffer,程序对标准输入输出的操作都会重定向到这里。再执行一次该命令则会隐藏。

6.2 输入数据

需要输入数据的时候,只需要在IO buffer中输入数据回车即可。已经输入的数据会被加粗,以和输出信息区分开来。

6.3 重定向到文件

有时候我们已经准备好了用于输入的数据在文件中,以避免调试时烦琐的输入。这时候就需要在调试时进行输入输出重定向了。

要进行重定向,只能使用gdb自带的功能。在gdb buffer中输入 run < data.in > data.out 就可以将标准输入重定向到data.in,将标准输出重定向到data.out了。

7 按键绑定

说实话,gud自带的按键绑定实在是麻烦,使用一个功能要三次组合键才行,小姆指按Ctrl都按酸了。所以一般将常用的按键绑定在方便的位置,这样才能有和另的IDE一样的快感。

以下是将F5、F7、F8分别绑定到gud-go、gud-step和gud-next的代码:

1
2
3
4
(add-hook 'gdb-mode-hook '(lambda ()
                            (define-key c-mode-base-map [(f5)] 'gud-go)
                            (define-key c-mode-base-map [(f7)] 'gud-step)
                            (define-key c-mode-base-map [(f8)] 'gud-next)))

之所以绑定到c-mode-base-map上,是因为我基本上在代码buffer中调试。如果要在gdb-buffer中使用的话,需要使用gud-mode-map。如果想在所有buffer上使用的话,可以绑定到全局按键中:

(global-set-key [(f5)] 'gud-go)

8 结尾

有了调试功能,Emacs作为一个IDE才算是完整了。本文介绍了在Emacs下使用gdb调试的基本方法,Emacs的调试功能还远不止这些,进一步学习可参阅 Emacs ManualDebuggers 一节。

由于我也是边学边写,一定有许多不足或者错误,还请各位多多指教。

Footnotes:

1 注:我在使用时只有光标所在的行在当前行之后并且位于同一函数内才行,否则会跳到很奇怪的地方,还请高手指教。

2 我在使用过程中经常出现展开没反应,或者加入新元素后才展开,运行几步才展开的情况,求高人讲解。

分享家:Addthis中国
GD Star Rating
loading...
在Emacs中使用gdb调试程序, 8.9 out of 10 based on 23 ratings 标签:ann, CEDET, ctrl, ede, Emacs, gdb, gud, IDE, lambda, org, screenshot, speedbar, text, windows, 光标, 工具栏, 补全, 配色, 鼠标

相关日志

分类: IDE, 中级
  1. 匿名
    2012年3月24日18:13 | #1

    爱学…爱学…但是你的配置bug一大堆..没有你的个别指点..学不通呀…再问下.c-x F要怎么使用呢?

    [回复]

  2. 匿名
    2012年3月25日21:26 | #2

    Wrong type argument: commandp, find-grep-in-current-dir ahei…为什么find-grep-in-current-dir用不了呀.

    [回复]

  3. 匿名
    2013年4月6日11:31 | #3

    :wink: 很有用~ 照着做基本就懂了。

    [回复]

  4. 2015年10月10日19:59 | #4

    I really like your writing style, superb information, appreciate it for putting up : D.

    [回复]

  5. 2016年4月7日06:22 | #5

    Fannie Mae and Federal National Mortgage Association to Amanda Elliston, 12 Glenn Drive, $185,000. michael kors handbags What s to love: Sing in the shower, listen to favorite tunes or the morning news through a Bluetoothenabled device that doesn t take up counter space. g http://www.coachoutletsonlines.us.org
    A strong dollar and faltering global growth have already cut into exports of factory goods louis vuitton outlet online Going into the semifinal we will have to work on some things,” said Palmer.
    Joanna Perl, Brian M. Perl and Joanna Sroka to Jozef Wegiel, 517 Ideal Lane, Unit 706, $250,000. cheap jordans Robin was the kind of guy you could go to if you were going to lose your house or if you had to have an operation or if your kid needed brain surgery. y coach bags
    The doctor must then make the decision of whether or not to help the patient into death by providing the lethal dose of medication coach outlet The single, bottom-mounted speakers in the S7 and S7 Edge, however, are a pleasant surprise.
    d Kristie L. Larosa, Kristie L. Bedinelli and Sebastiano Larosa to Jennifer V. Gautier, 299 Newbury St., $172,000. coach factory outlet Thousands of migrants are stranded in Greece. coach outlet store online
    These viruses may put people at risk and can cause serious illness or death coach outlet store online He also said he wanted to increase funding for the Arizona Department of Water Resources. http://www.raybanoutlet.name
    Working with pregnant women is gratifying, he added, because two lives benefit from treatment. michael kors outlet Instead, he supports having the coverage start at the time of the application. a coach outlet online
    “I guess it is on one level or another troubling,” Hetherington said stressing the importance of acknowledging “where it all started. cheap louis vuitton bags Michael Reagan and the president’s other son, Ron Prescott Reagan, are expected at Friday’s funeral.
    That sounds all nice and good and whatnot, but it just isn’t the whole picture, sadly. michael kors outlet online “There is nothing in the monthly report that would cause me to deviate from our conservative approach as we enter next month’s fiscal session,” which starts April 13.
    Lale (Günes Sensoy), Nur (Doga Doguslu), Ece (Elit Iscan), Selma (Tugba Sunguroglu) and Sonay (Ilayda Akdogan) engage in some mild capers on the way home to their small Turkish village for the summer, swimming with boys and stealing apples from a farm. coach outlet store online Monday’s resultsSoftballRINCON/UNIVERSITY 8, CHOLLA 0Rincon 321 000 2 8 11 0Cholla 000 000 0 0 0 2W Tanner (1-1).
    When the game is over, each player counts the number of vacant dots inside his or her territory. http://www.michaelkorshandbagstrade.us.com “It was a binding agreement, specifying the rent, the term of the lease and the square footage.
    b Run before sunrise. oakley glasses These are some of the most aggressive military actions in Somalia since a U.
    And worst of all there was nothing I could do about it. cheap michael kors bags RBNZ SURPRISES WITH RATE CUT The big surprise in Asia on Thursday came from New Zealand’s central bank, which cut the benchmark cash rate to a record low 2. o michael kors outlet
    com, LP. coach outlet store Meanwhile, the Supreme Electoral Court is considering a case that could, eventually, result in judges declaring Rousseff’s 2014 reelection to a second term invalid.
    e END 3: Western 47, East English 45 http://www.raybansunglasses.name The concert is part of the university s 201516 concert series. k
    Will a general-purpose weed and feed fertilizerherbicide take care of the weeds or should I use another product? When should I apply? Last year I removed the weeds by pulling them out by hand. michael kors handbags I watch carefully to keep both of her “wings” free. oakley sunglasses
    Kathleen A. Kerrigan and Raymond Magauran to Susan K. Orr and Sterling A. Orr II, 165 Converse St., Unit 3, $210,000. cheap jordan shoes “The current situation . f michael kors bags
    There will also be more LT models like the 675LT. michael kors outlet store There was no bump this time.
    Thank You Sir! GO BEAVERS! cheap michael kors bags “To me, this is not the end of anything,” Griffin said. m michael kors outlet
    More information can be found at louis vuitton outlet Sahuaro at Flowing Wells, 6 p.

    [回复]

  6. 2016年4月7日21:18 | #6

    The same year Seau died, Joseph Chernach, who had played football since he was a young boy and became an Upper Peninsula high school football star, killed himself at age 25. significant evidence of CTE and brain damage. His mother, Debra Pyka, said he never had a confirmed concussion. http://www.raybanoutlet.name I can name you about five marathons in Arkansas. m michael kors outlet store
    About six years ago, the brothers opened the John’s Diner at 146 Sheraton Drive. coach outlet store online More info here.
    – Their defense needs to force turnovers. I don’t see Oregon consistently stopping Stanford otherwise. coach outlet store There will be live music on the Friday performance, which is sure to give you tingles. s michael kors outlet store
    “As Allegheny County GOP] chairman, however, cheap louis vuitton bags In addition, under the new health care law, check on Covered California or through your insurance advisor to see if there is a plan that is equal to or better than yours with a lower premium.
    y “My dad passed away last fall. He never got to see the book. He was a visionary,” Rose shared when we had stopped to taste the green, spicy leaves of the monardo fistulosa, while a handful of bumblebees lit on its pink blossoms. louis vuitton outlet When it comes to food, I think that s a common desire. michael kors outlet online
    BIGSKY-N COLORADO-PORTLAND ST coach outlet He hit his first MLB home run in his second game with New York on July 12. http://o.westboroughpolice.com
    Here’s a look at the week forboth players: coach outlet store online BENTONVILLE Gov. a coach online store
    Nigel Bradham: Easily the most productive season of Bradham’s four-year career came in 2014, his one season playing under new Eagles defensive coordinator Jim Schwartz in Buffalo. ray ban outlet It’s not a trend,” he said.
    It completely seized up. ray ban outlet Additionally, Arkansas school districts are seeking state approval for proposed conversion charter schools that would begin operating in 201718.
    The NFL’s testing for PEDs are a complete joke compared to the standards for MLB, let alone track and field and cycling. louis vuitton outlet p class MsoNormal”!–!supportEmptyParas]–? !—-style video-ad-asset-container, video-ad-asset-container-played max-height: 0px; overflow: hidden; -webkit-transition: max-height 1s; -moz-transition: max-height 1s; transition: max-height 1s; video-ad-asset-container.
    “He added: “We have identified four priority areas where we can make the biggest environmental and economic impact: food and drink, energy infrastructure, remanufacturing and construction. nfl jerseys He had served in the U.
    q Executives for Faraday Future sent a letter to Nevada officials this week promising to help guarantee some of the $120 million in public investments in infrastructure at the Apex Industrial Park in North Las Vegas. cheap jordan shoes Augustine’s parish hall, a facility not large enough to serve the 800 to 1,000 families in the parish, much less the diocese as a whole, Kicanas said.
    “If China had a very significant and prolonged devaluation, it would in essence spread deflation around the world,” Wheeler told reporters, adding that China was building up a number of serious imbalances. nfl jerseys San Juan School, like other sites across the state, has been plagued with staffing issues this year. x louis vuitton handbags
    “Our fans deserve better. oakley sunglasses There’s a ripple effect from this class that will be felt for many years.
    x Bell is expected to miss at least a few more weeks and Ennis could be out until January. coach outlet online Cruz needed his win in Texas in order to stay in the race. j
    “Instead of keeping the books out of children’s hands for the two years of the renovation we wanted to make sure the children had them now,” he explained. louis vuitton handbags “Jhoulys Chacin (2-1) went three innings to earn the win. http://www.coachstoresonline.com
    Here’s a breakdown of the appointment timeline and process: michael kors outlet Experts from a Washington, D. v http://www.michaelkorsbag.us.org
    And they get a tasty lesson in healthy eating with a fun snack each time. michael kors outlet online But this apartment case is difficult.
    Eminem is the Executive Producer of the movie soundtrack which includes two tracks from the multi-platinum rapper, “Phenomenal,” and “Kings Never Die,” featuring Gwen Stefani. louis vuitton outlet online Anger = more trouble d coach outlet online
    (ABC7) — The news from Hagerstown wasn’t good. http://www.michaelkorshandbagsbuy.us.com LOS ANGELES John Gibson made 28 saves in his dynamic NHL playoff debut, captain Ryan Getzlaf had a goal and an assist, and the Anaheim Ducks evened their second-round playoff series with a 2-0 victory over the Los Angeles Kings in Game 4 on Saturday night.

    [回复]

评论分页
1 2 3 41056
  1. 2010年3月29日02:24 | #1
  2. 2012年5月12日23:07 | #2
  3. 2012年11月3日15:59 | #3
  4. 2014年6月22日13:28 | #4
:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: