Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming: How to use gdb with Makefile and command line arguments?

To create the .out executable, I have to enter:

$: make
$: myprogram.out name.ged

My program incorporates a command line argument, thus the "name.ged".

Whenever I run gdb after getting a segmentation fault (core dumped), I enter:

$: gdb a.out core
(gdb): bt

I then use the back trace command, and gdb returns:

#0 0x4a145155 in ?? ()
#1 0x08a16ce0 in ?? ()

I even tried using the up command t move up the stack, but still no luck. I can't tell which line in my program is giving me the seg fault. gdb works with my other programs that do not involve a Makefile and command arguments, so I'm wondering if my commands are incorrect.

like image 441
Bonnie Avatar asked Mar 07 '13 00:03

Bonnie


1 Answers

Summarizing the comments (before anyone else does :).

Your executable file is missing the symbolic information that gdb needs to display the relevant source code. You need to add the -g option to the compile command and produce a new executable. Then re-run your failing test to produce a new core file. gdb with this executable and core will be able to show you the stack of function calls using backtrace.

In a makefile, the easiest way to do this is to add (to) the CFLAGS variable which is used with the implicit .o.c rule.

CFLAGS= -g -Wall -Wextra

You can also add this directly to the command-line (assuming a decent shell :). This sets the value as an environment variable during the execution of the make command (and sub-commands).

$ CFLAGS='-g -Wall -Wextra' make

I'd actually recommend you add this to your bash .profile, so you always get the most information from the compiler.

CFLAGS='-Wall -Wextra'

Then, when you need it, put this in the makefile to make a debuggable executable:

CFLAGS+= -g
like image 149
luser droog Avatar answered Oct 05 '22 03:10

luser droog