4

Is it possible to add GDB breakpoints in a C files, before compilation? Currently, I have to specify breakpoints after compilation through GDB.

I'm looking for something similar to JavaScript's debugger; statement.

Randomblue
  • 112,777
  • 145
  • 353
  • 547

3 Answers3

5

Not as such, but you can insert some helpful function calls:

One option is to create a function:

void break_here ()
{
  /* do nothing */
}

then call it wherever you want, but be careful it doesn't get inlined (put it in a different file, or add a "noinline" attribute).

Then, in GDB, just set a breakpoint on break_here, and you're done. If you find it tedious to set that breakpoint every time, you can create a file named .gdbinit in your home directory or in the current working directory that contains the breakpoint command.

Another option that works on Linux is to use a signal:

raise (SIGUSR1);

You could use any signal you like, but it's better to use one that doesn't kill your program (although you can configure GDB to not pass them onto your program, if you choose).

ams
  • 24,923
  • 4
  • 54
  • 75
  • Exactly the same, I think, although I vaguely remember that Windows had a different filename? GDB uses your `$HOME` variable for the location of the home directory. – ams Mar 12 '12 at 17:30
  • Ah, just looked it up: Windows *might* use gdb.ini as the file name, but it's just a GDB script inside. – ams Mar 12 '12 at 17:31
  • 2
    Declare the function like so: `void break_here ( void ) __attribute__ ((optimize(0)));`. Just using `__attrubute__((noinline))` will not prevent GCC from optimizing the call away completely. Alternatively, this line will turn off optimization for the rest of the source file: `#pragma GCC optimize("0")`, which is useful if you want to debug one module in an otherwise optimized build. – Brian McFarland Mar 12 '12 at 18:33
2

I'm not aware of a way to directly set a breakpoint, but GDB will catch interrupts, so that is one possible solution.

Something like this should work. You'll need to include signal.h:

raise(SIGABRT);
jncraton
  • 9,022
  • 3
  • 34
  • 49
1

on linux, which I'm assuming you're on since you're using gdb you could make a script to do it with comments in the code

#!/bin/bash
#debug: Script to run programs in gdb with comments to specify break 
points
echo "file ./a.out" > run
grep -nrIH "/\*GDB\*/" |
    sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
    awk '{print "b" " " $1 }'|
    grep -v $(echo $0| sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r
exit 0

then wherever you need a breakpoint, just add /*GDB*/, the script will use grep to find the line numbers and files with those comments, and set a break point on each line of each file it finds them on, then start gdb

Austin_Anderson
  • 900
  • 6
  • 16