如何在 GDB 中自动运行可执行文件?

我想让 gdb立即运行可执行文件,就像我输入“ run”一样 (动机: 我不喜欢输入“ run”)。

一种方法是像下面这样将命令通过管道发送到 gdb:

$ echo run | gdb myApp

但是这种方法的问题是你会失去与 gdb的交互性, 例如,如果断点触发器或 myApp崩溃,gdb退出。 讨论了这种方法的 给你

看看 --help中的选项,我看不出有什么方法可以做到这一点,但也许我遗漏了什么。

43397 次浏览

I would use a gdb-script:

gdb -x your-script

where your-script contains something like:

file a.out
b main
r

afterwards you have the normal interactive gdb prompt

EDIT:

here is an optimization for the truly lazy:

  1. save the script as .gdbinit in the working directory.
  2. Afterwards you simply run gdb as

    gdb

... and gdb automatically loads and executes the content of .gdbinit.

gdb -ex run ./a.out

If you need to pass arguments to a.out:

gdb -ex run --args ./a.out arg1 arg2 ...

EDIT: Orion says this doesn't work on Mac OSX.

The -ex flag has been available since GDB-6.4 (released in 2005), but OSX uses Apple's fork of GDB, and the latest XCode for Leopard contains GDB 6.3.50-20050815 (Apple version gdb-967), so you are out of luck.

Building current GDB-7.0.1 release is one possible solution. Just be sure to read this.

(echo r ; cat) | gdb a.out

The cat allows you keep typing after gdb breaks.

gdb -x <(echo run) --args $program $args

start command

This command is another good option:

gdb -ex start --args ./a.out arg1 arg2

It is like run, but also sets a temporary breakpoint at main and stops there.

This temporary breakpoint is deactivated once it is hit.

starti

There is also a related starti which starts the program and stops at the very first instruction instead, see also: Stopping at the first machine code instruction in GDB

Great when you are doing some low level stuff.