Usage of GCC gdb

Source: Internet
Author: User
Tags ftp site function prototype int size
usage of gcc gdb

Introduces the basic usage of GCC and GDB
Objective

Linux distributions contain a lot of software development tools. Many of them are used in C and C + + application development. This article describes the tools that can be used for C application development and debugging under Linux. The thrust of this article is to explain how to use the C compiler and other C programming tools under Linux, rather than the C programming tutorials. In this article you will learn the following knowledge:

What is C

GNU C Compiler
Debugging GCC applications with GDB
You can also see other useful C programming tools that are distributed with Linux. These tools include the source program beautification program (pretty print programs), the additional debugging tools, the function prototype automatic generation tool (Automatic function prototypers).

Note: The source program beautification program (pretty print programs) automatically formats your source code to produce consistent indentation.


What is C?

C is a general-purpose programming language that is widely used in the early days of the UNIX operating system. It was first written by the Dennis Ritchie of Bell Labs for the auxiliary development of UNIX, and Unix was written in assembly language and a word called B in the beginning. Since then, C has become the most widely used computer language in the world.
The reasons why C can be so widely supported in the programming world are as follows:
It is a very common language. Almost any computer you can think of has at least one available C compiler. and its syntax and function libraries are unified on a variety of platforms, and this feature is appealing to developers.
Programs written in C are fast to execute.
C is the system language on all versions of UNIX.
C has made great progress in the past 20 years. In the late 80, the American National Standards Institute (American Nation Standards Institute) released a C language standard called ANSI C. This will ensure the future consistency of C on different platforms. In the 80 's there was also a C-object-oriented extension called C + +. C + + will be described in another article, "C + + programming."
The C compiler available on Linux is the GNU C compiler, which builds on the Free Software Foundation's programming license and is therefore free to release. You can find it on the Linux release CD.

GNU C Compiler

The GNU C compiler (GCC) issued with Slackware Linux is a fully functional ANSI C-compliant compiler.
If you are familiar with a C compiler on another operating system or hardware platform, you will soon be able to master GCC.

This section describes how to use GCC and some of the GCC compilers ' most common options.

Using GCC is usually followed by some options and file names to use the GCC compiler. The basic usage of the GCC command is as follows:
gcc [options] [filenames]
The actions specified by the command-line option are executed on each given file on the command line. The next section will describe some of the options that you will most commonly use.

GCC Options

GCC has more than 100 compilation options available. Many of these options may never be used, but some of the major options will be used frequently. Many of the GCC options include more than one character.
So you have to specify individual hyphens for each option, and just like most Linux commands you can't have a single hyphen followed by a set of options. For example, the following two commands are different:
Gcc-p-G test.c

GCC-PG test.c
The first command tells GCC to create profiling (profile) information for the Prof Command when compiling test.c and to add debug information to the executable file. The second command only tells GCC to establish profiling information for the gprof command.
When you compile a program without any options, GCC will build (assuming the compilation succeeds) a executable file named A.out. For example, the following command will produce a file called A.out in the current directory:
GCC test.c You can use the-O compilation option to specify a filename for the resulting executable file instead of a.out. For example, to compile a C program called Count.c into an executable named count, you would enter the following command:
Gcc-o Count Count.c

Note: When you use the-o option,-o must follow a filename.

GCC also has the compiler option to specify how much the compiler handles. The-C option tells GCC to skip compilation and connection only by compiling the source code into the target code.
This option is used very frequently because it makes compiling multiple C programs faster and easier to manage. By default, the target code file that GCC establishes has an. o extension.
The-S compilation option tells GCC to stop compiling after generating assembly language files for C code. The default extension of the assembly language file produced by GCC is. S. -E
option instructs the compiler to preprocess only the input file. When this option is used, the output of the preprocessor is sent to the standard output instead of being stored in the file.

Optimization options

When you compile C code with GCC, it tries to compile with minimal time and make the compiled code easy to debug. Easy debugging means that the compiled code has the same order of execution as the source code, and the compiled code is not optimized. There are a number of options available to tell GCC to generate smaller, faster executables on a more compile-time basis and at the expense of easy debugging. The most typical of these options are the-O and-O2 options.
The-o option tells GCC to base optimization on the source code. These optimizations make the program perform faster in most cases. The-O2 option tells GCC to produce as little and as fast code as possible.
The-O2 option will make compilation slower than when using-O. Often, however, the resulting code executes more quickly.
In addition to the-O and-o2 optimization options, there are low-level options for generating faster code. These options are very special, and it's best to use them only when you fully understand how these options will affect the compiled code. For a detailed description of these options, refer to the GCC Guide page and type man gcc on the command line.

Debugging and profiling options

GCC supports a number of debugging and profiling options. The G-and-PG options are most commonly used in these options.
The-G option tells GCC to generate debug information that can be used by the GNU debugger to debug your program. GCC provides a feature that is not available in many other C compilers where you can use the-G and-O (generating optimized code). This is useful because you can debug your code as closely as possible with the final product.
When you use both options you must be aware that some of the code you write has been modified by GCC during optimization. For more information about debugging C programs, see the next section, "Debug C programs with GDB."
The-PG option tells GCC to add extra code to your program, and then generate gprof profiling information to show how time-consuming your program is. For more information on Gprof, refer to the "Gprof" section.

Debugging GCC programs with GDB

Linux contains a GNU debugger called GDB. GDB is a powerful debugger for debugging C and C + + programs.
It allows you to observe the internal structure and memory usage of the program while the program is running. Here are some of the features GDB provides:
It allows you to monitor the value of variables in your program.
It allows you to set breakpoints so that the program stops executing on the specified line of code.
It allows you to execute your code in a row.

You can run GDB by typing gdb on the command line and pressing ENTER, and if everything works, GDB will be started and you will see something similar on the screen:
GDB is free software and your are welcome to distribute copies of it
Under certain conditions; Type ' show copying ' to the conditions.

There is absolutely no warranty for GDB; Type ' show warranty ' for details.

GDB 4.14 (I486-slakware-linux), Copyright 1995 free Software Foundation, Inc.

(GDB)

When you start GDB, you can specify a number of options on the command line. You can also run gdb in the following ways:

Gdb
When you run GDB this way, you can directly specify the program you want to debug. This tells GDB to mount the executable file named FName. You can also use GDB to check for a core file that was generated by an abnormal termination of the program, or to connect to a running program. You can refer to the GDB Guide page or type gdb-h on the command line to get a simple list of instructions for these options.

Compiling code for debugging (compiling code for debugging)
In order for GDB to work correctly, you must make your program include debugging information at compile time. The debug information contains the type of each variable in your program and the address mapping in the executable file and the line number of the source code.
GDB uses this information to correlate the source code with machine code.
The debug option is turned on at compile time with the-G option.

GDB Basic Command

GDB supports a number of commands that enable you to implement different functions. These commands are loaded from simple files into complex commands that allow you to check the contents of the stack being invoked, and table 27.1 lists some of the commands you'll use when debugging with GDB. For more information about GDB, refer to the GDB Guide page.

Table 27.1. Basic GDB command.

Command description

File loads the executable file you want to debug.
Kill terminates the program that is being debugged.
List lists part of the source code that generated the execution file.
Next executes a line of source code but does not go inside the function.
Step executes a line of source code and goes inside the function.
Run executes the program that is currently being debugged
Quit Terminate GDB
Watch allows you to monitor the value of a variable regardless of when it is changed.
The break sets a breakpoint in the code, which causes the program to be suspended when it is executed here.
Make enables you to recreate the executable file without exiting GdB.
The shell allows you to execute UNIX shell commands without leaving GDB.

GDB supports many of the same command-editing features as UNIX shell programs. You can press the TAB key as you would in bash or tcsh to get gdb to help you with a unique command, if not unique, GDB lists all the matching commands. You can also flip the history commands up and down with the cursor keys.

Example of GDB application

This is a practical example to teach you step-by-step debugging programs with GDB. The program being debugged is fairly simple, but it shows the typical application of GDB.

The following is a list of the programs that will be debugged. This program, called greeting, displays a simple greeting and then lists it in reverse order.
#include

Main ()

{

Char my_string[] = "Hello there";

My_print (my_string);

My_print2 (my_string);

}

void My_print (char *string)

{

printf ("The string is%s/n", string);
  
}

void My_print2 (char *string)

{

Char *string2;

int size, I;

Size = strlen (string);

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size-i] = String[i];

STRING2[SIZE+1] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}

Compile it with the following command:
Gcc-o Test test.c
This program is executed with the following results displayed:
The string is hello there

The string printed backward is
The first line of output is correct, but the second line of print is not what we expected. The output we envision should be:
The string printed backward is Ereht Olleh
For some reason, the My_print2 function does not work properly. Let's use GDB to see where the problem is, and first type the following command:

GdB Greeting

Note: Remember to turn on the debug option when compiling the greeting program.

If you forgot to pass the program you want to debug as an argument to GDB when you entered the command, you can load it with the file command at the GDB prompt:
(gdb) file greeting
This command will load the greeting executable as if you were loading it in the GDB command line.
Then you can run greeting with GDB's Run command. When it is run in gdb it will be like this:
(GDB) Run

Starting program:/root/greeting

The string is hello there

The string printed backward is

Program exited with code 041
This output is the same as the result of running outside of GDB. The question is, why is reverse-order printing not working? To find the sticking point, we can set a breakpoint on the MY_PRINT2 function's for statement, by typing the list command three times at the GDB prompt, listing the source code:
(GDB) List

(GDB) List

(GDB) List

Tip: At the GDB prompt, press RETURN to repeat the previous command.

The first time you type the output of the list command is as follows:

1 #include

2

3 Main ()

4 {

5 char my_string[] = "Hello there";

6

7 My_print (my_string);

8 My_print2 (my_string);

9}

10
If you press ENTER, GDB executes the list command again, giving the following output:

One my_print (char *string)

12 {

printf ("The string is%s/n", string);

14}

15

My_print2 (char *string)

17 {

*string2 Char;

int size, I;

20
Press RETURN again to list the remaining parts of the greeting program:
Size = strlen (string);
  
string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size-i] = String[i];

STRING2[SIZE+1] = '/0 ';

Num printf ("The string printed backward is%s/n", string2);

27}
Depending on the source program listed, you can see where to set the breakpoint on line 24th, type the following command at the GDB command prompt to set the breakpoint:
(GDB) Break 24
GDB will respond as follows:
Breakpoint 1 at 0x139:file greeting.c, line 24

(GDB)

Now you type the Run command, which produces the following output:

Starting program:/root/greeting

The string is hello there

Breakpoint 1, My_print2 (string = 0xbfffdc4 "Hello there") at greeting.c:24

String2[size-i]=string[i]
You can see how the error arises by setting an observation point that observes the value of the string2[size-i variable, by typing:

(GDB) Watch String2[size-i]
GDB will respond as follows:
Watchpoint 2:string2[size-i]
You can now use the next command to perform a for loop step-by-step:

(GDB) Next
After the first loop, GdB tells us that the value of string2[size-i] is ' h '. GdB tells you this information using the following display:

Watchpoint 2, String2[size-i]

Old value = 0 '/000 '

New value = ' h '

My_print2 (string = 0xbfffdc4 "Hello there") at greeting.c:23

The value for i=0 I is expected. The results of the subsequent cycles are correct. When i=10, the value of the expression string2[size-i] equals ' e ', the size-i value equals 1, and the last character is copied to the new string.
If you run the loop again, you will see that there is no value assigned to string2[0], and it is the first character of the new string, because the malloc function initializes them to null (NULL) characters when allocating memory. So the first character of the string2 is a null character. This explains why there is no output when printing string2.
It's easy to fix the problem by figuring out where it is. You have to change the offset of the first word written to string2 in the code Fu to size-1 instead of size.
This is because the size of the string2 is 12, but the starting offset is 0, and the characters within the string are retained from offset 0 to offset 10, and offset 11 as empty characters.
There are many ways to modify the code to work properly. One is to set a variable that is 1 more than the actual size of the string. This is the code for this workaround:
#include

Main ()

{

Char my_string[] = "Hello there";

My_print (my_string);

My_print2 (my_string);

}

My_print (char *string)

{

printf ("The string is%s/n", string);

}

My_print2 (char *string)

{

Char *string2;

int size, size2, I;

Size = strlen (string);

Size2 = size-1;

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size2-i] = String[i];

String2[size] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}
The other C programming tools
The Slackware Linux distribution also includes some of the C development tools that we have not yet mentioned. These tools and their typical usage are described in this section.

Xxgdb

XXGDB is a graphical interface for GDB based on the X Window system. Xxgdb includes all of the features on GDB on the command-line version. XXGDB enables you to perform commonly used commands by pressing the button. The place where the breakpoint is set is also shown graphically.

You can run it in a Xterm window by typing the following command:
Xxgdb
You can initialize XXGDB with any valid command-line options in GDB. In addition Xxgdb has some specific command-line options, which are listed in table 27.2.

Table 27.2. XXGDB command line Options.


Option description

DB_NAME Specifies the name of the debugger you are using, and the default is GDB.
DB_PROMPT Specifies the debugger prompt, and the default is GDB.
GDBINIT Specifies the file name of the command file that initializes gdb, by default. Gdbinit.
NX tells Xxgdb not to execute. gdbinit files.
Bigicon use large icons.

Calls

You can use the following path at the sunsite.unc.edu FTP site:
/pub/linux/devel/lang/c/calls.tar.z
To get calls, some of the older Linux CD-ROM distributions are also included. Because it is a useful tool, we also introduce here.
If you think it's useful, get a copy from BBS, FTP, or another CD-ROM. Calls invokes the GCC preprocessor to process the given source program files, and then outputs the function call tree diagram in the files.

Note: Install calls on your system, log in as Superuser, and perform the following steps: 1. Extract and Untar files. 2. A subdirectory established after the CD enters the calls Untar. 3. Move the file named calls to the/usr/bin directory. 4. Move the file named Calls.1 to the directory/usr/man/man1. 5. Delete the/tmp/calls directory. These steps will install the calls program and its guide page on your system.

When calls prints out the call trace result, it gives the filename of the file that contains the function in parentheses after the function:
Main [test.c]
If the function is not in the file given to calls, calls does not know where the called function comes from, only the name of the function is displayed:
Printf
Calls does not output recursion and static functions. The recursive function appears as follows:
Fact <<< recursive in FACTORIAL.C >>>
Static functions appear like this:
Total [static in calculate.c]
As an example, suppose you use calls to process the following program:

#include

Main ()

{

Char my_string[] = "Hello there";

My_print (my_string);

My_print2 (my_string);

}

My_print (char *string)

{

printf ("The string is%s/n", string);

}

My_print2 (char *string)

{


int size, size2, I;

Size = strlen (string);

Size2 = size-1;

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size2-i] = String[i];

String2[size] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}
will produce the following output:
1 main [test.c]

2 My_print [test.c]

3 printf

4 My_print2 [test.c]

5 strlen

6 malloc

7 printf
Calls has a number of command-line options to set different output formats, please refer to the Calls Guide page for more information on these options. To do this, type calls-h on the command line.

Cproto

Cproto reads the C source program file and automatically generates a prototype declaration for each function. With Cproto, you can save a lot of time to define a function prototype when writing a program.
If you let Cproto process the following code:
#include

Main ()

{

Char my_string[] = "Hello there";

My_print (my_string);

My_print2 (my_string);

}

My_print (char *string)

{

printf ("The string is%s/n", *string);

}

My_print2 (char *string)

{

Char *string2;

int size, size2, I;

Size = strlen (string);

Size2 = size-1;

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size2-i] = String[i];

String2[size] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}
You will get the following output:
* TEST.C * *

int main (void);

int My_print (char *string);

int My_print2 (char *string);
This output can be redirected to a containing file that defines the prototype of the function.

Indent

The indent utility is another programming utility that is included in Linux. The tool simply says that it produces a nice indented format for your code. Indent also has a number of options to specify how to format your source code. For more information on these options, see the Indent Guide page and type indent-h on the command line.

The following example is the default output for indent:
Run Indent's previous C code:
#include

Main () {

Char my_string[] = "Hello there";
  
My_print (my_string);

My_print2 (my_string); }

My_print (char *string)

{

printf ("The string is%s/n", *string);

}

My_print2 (char *string) {

Char *string2;

int size, size2, I;

Size = strlen (string);

Size2 = size-1;

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size2-i] = String[i];

String2[size] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}
C code after running indent:
#include

Main ()

{

Char my_string[] = "Hello there";

My_print (my_string);

My_print2 (my_string);

}

My_print (char *string)

{

printf ("The string is%s/n", *string);

}

My_print2 (char *string)

{

Char *string2;

int size, size2, I;

Size = strlen (string);

Size2 = size-1;

string2 = (char *) malloc (size + 1);

for (i = 0; i < size; i++)

String2[size2-i] = String[i];

String2[size] = '/0 ';

printf ("The string printed backward is%s/n", string2);

}
Indent does not change the actual content of the code, but only changes the appearance of the code. Make it more readable, it's always a good thing.

Gprof

Gprof is a program installed in the/usr/bin directory of your Linux system. It allows you to dissect your program to know which part of the program is most time-consuming to execute.
Gprof will tell you the number of times each function is invoked in the program and the percentage of time it takes to execute each function. This information is useful if you want to improve your program's performance.
In order to use GPROF on your program, you must add the-PG option when compiling the program. This causes the program to produce a file called gmon.out each time it is executed. Gprof Use this file to generate profiling information.
After you run your program and generate a Gmon.out file, you can get profiling information using the following command:
Gprof
Parameter program_name is the name of the program that produces the Gmon.out file.

Tip: Gprof produces a lot of profiling data, and if you want to check the data, it's best to redirect the output to a file.

F2C and P2C

F2C and P2C are two source code converters. F2C the FORTRAN code into C code, P2C to convert Pascal code to C code.
When you install GCC, both programs will be installed.
If you have some code written in FORTRAN or Pascal to rewrite in C, f2c and p2c are very useful to you. The C code produced by these two programs can be compiled directly by GCC without modification.
If you want to convert FORTRAN or Pascal program is relatively small, you can directly use F2C or p2c without any option. If the program you want to convert is large and contains a lot of files, you might want to use some command-line options.
To use F2C on a FORTRAN program, enter the following command:
F2C MY_FORTRANPROG.F


Note: F2C requires the program to be converted with the extension. f or a. F.

To replace a Pascal program with a C program, enter the following command:
P2C My_pascalprogram.pas
Both programs produce the same file name of C source code as the original filename, but the extension is changed from. F or. pas to. c.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.