5

I have c++ program which I run by passing string with it.

g++ -o a main.cpp -lpthread

and execute it with ./a "Good nice"

But how I debug it with gdb? main.cpp calling functions from other files which are included in it.

gdb ./a "Good nice"

takes "--" as files and says no such file!

I want to debug line by line!

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user123
  • 5,269
  • 16
  • 73
  • 121
  • possible duplicate of [Passing arguments to program run through gdb](http://stackoverflow.com/questions/4521015/passing-arguments-to-program-run-through-gdb) – mmmmmm Aug 17 '13 at 07:49
  • Also compile your program with `-g` otherwise this is all for nothing – aaronman Aug 17 '13 at 07:54

4 Answers4

6

Use the --args option of gdb:

gdb --args ./a "Good nice"

Also add the -g option to your compiler call, because otherwise gdb won't be able to connect your executable with your source code:

g++ -g -o a main.cpp -lpthread
Macmade
  • 52,708
  • 13
  • 106
  • 123
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106
  • he also has to compile with `-g` – aaronman Aug 17 '13 at 07:49
  • @aaronman yes, to be able to use the debugger at all. But wasn't this question about the program arguments problem? – cmaster - reinstate monica Aug 17 '13 at 07:50
  • If he shows you how he's compiling it and you know it's wrong and you don't tell him, is your answer useful? – aaronman Aug 17 '13 at 07:51
  • 2
    If we are at it, you should also add -Wall... ;-) – László Papp Aug 17 '13 at 09:03
  • @LaszloPapp Cheers :D but I think that would really start going off topic. I can upvote your comment, though. – cmaster - reinstate monica Aug 17 '13 at 09:10
  • first `g++ -g -o b main.cpp foo.cpp` then `gdb --args ./b "good nice" `. Then `s` for line by line execution gives `the program is not being run` – user123 Aug 17 '13 at 09:56
  • Well, in any case you need to say `run` to gdb before trying to step through a program. Before that, gdb does not start a process which you could debug. I know, it is awkward that gdb doesn't do this automatically when it starts, but that's the way it is. Likely, you'll want to set a breakpoint (`break`) after saying `run`, so that you don't have to step through your entire program to reach the interesting point, but that is optional, `run` breaks at the start of `main()`. Correct sequence: `g++ -g ...`, `gdb --args ...`, `run`, [`break ...`], all the other commands you use to debug your code. – cmaster - reinstate monica Aug 17 '13 at 12:50
5

Use gdb without argument

gdb ./a

Then in gdb, before running the program

set args "Good nice"

And you can see what arguments you set, use

show args

See here for detail.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
3

gdb ./prog -> set args string -> run.

elmov
  • 286
  • 1
  • 11
3

Anther choice is provide argument after run

$gdb ./a
 run "Good nice"
billz
  • 44,644
  • 9
  • 83
  • 100