Debugging with Emacs

Compile (say, files f1.cpp and f2.cpp) with the following command from Emacs:

M-x compile <return>

Compile command: g++ -o myprogram -g f1.cpp f2.cpp

The presence of ‘-g’ flag tells the compiler to generate the debug symbols in the generated executable called “myprogram“.

Now, invoke debugger from Emacs using the following command:

M-x gdb <return>

Run gdb (like this): gdb myprogram

[For Emacs running in windows mode, try using "--annotate=3" to set the annotate level to 3]

This brings you to gdb prompt, where you can run the program by typing ‘r’ as follows:

gdb> r

If you intend to debug your program, you will likely have a particular place to stop and inspect the variables under question. In that case, setting a breakpoint might be a good place to start before running the program.

Here is a table of gdb commands that you could run from Emacs (after generating the gdb prompt):

 

C-x <space> [Emacs Command] Go to any line in your source code and invoke this command to set a breakpoint. (This is the most convenient way to set a breakpoint from Emacs.)
gdb> b main Set a breakpoint in the beginning of main().
gdb> r Run till a breakpoint or run to completion.
gdb> c Continue from the current breakpoint.
gdb> s Step into a function.
gdb> n Step over the current line. When you hit “return”, the gdb executes the previous command, i.e., you keep executing the program line by line.
gdb> where Inspect the call stack.
gdb> p <varname> Prints the content of a variable called <varname>.
gdb> fin Step out of the current function.
gdb> i b List all the breakpoints.
gdb> del <bpid> Remove breakpoint number <bpid>.
gdb> dis <bpid> Disable breakpoint number <bpid>.
gdb> ena <bpid> Enable breakpoint number <bpid>. (You can toggle enabling and disabling the breakpoints using ena and dis commands.)
gdb> b <bpid> <condition> Set conditional breakpoint for breakpoint number <bpid>. (A condition could be any logical expression like ‘(<varname> == 3)’.)
gdb> comm <bpid> Execute a set of commands every time the execution halts at the breakpoint number <bpid>.

 

This entry was posted in Emacs. Bookmark the permalink.

Comments are closed.