UNIX & GNU/Linux - gdb - With Emacs

To start gdb, we have to add the -g flag at the compilation time.
So it is easy to add it in a Makefile. We are also using the Emacs IDE for running gdb.
Note that the code below does not work because we want to see the segmentation fault with gdb.

Let's create a main.c file in our gdb mini tutorial:

#include <stdio.h>
#include <string.h>

int main(int c, char *v[])
{
    char *string; int i;
    i = 0;
    while (i < strlen(v[1]))
    {
        printf("%c", string[i]);
        i++;
    }
    return (0);
}

Let see an example of the gdb using:

$ gcc -g main.c

Once our program is compiled we have to open the file we want to debug.
We can type :

$ gdb ./a.out

Or we can use Emacs, let's try it:
So we open the main.c file, then we have to active the meta X command by clicking: ALT + X At the bottom, M-x appears, write: gdb Click Enter, this line will appear: Run gdb (like this): gdb --annotate=3 a.out Reclick on Enter to validate.
You are now seing the licence and some information.
After the line (gdb) write run to start gdb.
The word gdb will replace the a.out.
To terminate gdb, just write quit.
You can use "backtrace" to see all files from where the bug comes.
Use "break main" to put a break point on the main function.
Use "next" to go to the next instruction.
Use "step" to see each line read.
Use "print i" to print the i variable of your code.
Use "display i" to display the i variable at each step without retype this command.

You can also use the first letter of the command if there is no ambiguity.
Example "n" for "next".
If you already write "next", just type ENTER to repeat this command.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.