Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GDB to debug a C++ program called from a shell script

I have a extremely complicated shell script, within which it calls a C++ program I want to debug via GDB. It is extremely hard to separate this c++ program from the shell since it has a lot of branches and a lot of environmental variables setting.

Is there a way to invoke GDB on this shell script? Looks like gdb requires me to call on a C++ program directly.

like image 362
CuriousMind Avatar asked Feb 19 '11 00:02

CuriousMind


People also ask

Does GDB work for C?

Gdb is a debugger for C (and C++). It allows you to do things like run the program up to a certain point then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line.

How do I run a GDB from a bash script?

You need to type run to execute the binary file in gdb . To automatically run the binary file once we run the bash script, we can add the -ex=r as shown below. Run the bash script. From the output, we can see that the binary file was run automatically without us having to type run in gdb .

What is a command in GDB that will bring your debugging into the function?

To debug your program in gdb, you have to run it by typing "run". However, if you just type "run" gdb will run your program to completion without debugging it at all. If your program crashes, gdb will stop it and allow you to debug it.


2 Answers

In addition to options mentioned by @diverscuba23, you could do the following:

gdb --args bash <script> 

(assuming it's a bash script. Else adapt accordingly)

like image 52
Vishal Avatar answered Sep 21 '22 12:09

Vishal


There are two options that you can do:

  1. Invoke GDB directly within the shell script. This would imply that you don't have standard in and standard out redirected.

  2. Run the shell script and then attach the debugger to the already running C++ process like so: gdb progname 1234 where 1234 is the process ID of the running C++ process.

If you need to do things before the program starts running then option 1 would be the better choice, otherwise option 2 is the cleaner way.

like image 25
diverscuba23 Avatar answered Sep 19 '22 12:09

diverscuba23