C language programming in Linux

Source: Internet
Author: User
Tags ftp site
C language programming in Linux-general Linux technology-Linux programming and kernel information. The following is a detailed description. The Linux release contains many software development tools. Many of them are used for C and C ++ application development. This article describes the tools that can be used for C application development and debugging in Linux. This document describes how to use the C compiler and other C programming tools in Linux, rather than programming in C. In this article, you will learn the following:

· What is C
· Gnu c Compiler
· Use gdb to debug GCC applications
You can also see other useful C programming tools released with Linux. These tools include the source program beautification program (pretty print programs), additional debugging tools, and automatic function prototypers ).

Note: The source program beautification program (pretty print programs) automatically helps you format the source code to generate consistent indent formats.

What is C?
C is a common programming language that was widely used in the early days of UNIX operating systems. It was first written by Dennis Ritchie of Bell Labs for UNIX-assisted development. At the beginning, UNIX was written in assembly language and a language called B. Since then, C has become the world's most widely used computer language.

The reasons why C is so widely supported in programming are as follows:
· It is a very common language. Almost any computer you can think of has at least one C compiler that can be used. In addition, its syntax and function libraries are unified on different platforms. This feature is very attractive to developers.
· Programs written in C run fast.
· C is the system language of all versions of UNIX.
C has experienced great development in the past two decades. At the end of 1980s, the American National Standards Institute released a C language standard called ansi c. This ensures the consistency of C on different platforms in the future. In 1980s, a C-oriented extension called C ++ emerged. C ++ will be described in another article "C ++ programming.
The available C compiler on Linux is the gnu c compiler, which is based on the programming license of the Free Software Foundation and can be freely released. You can find it on the Linux release CD.
Gnu c Compiler
The gnu c compiler (GCC) released with Slackware Linux is a fully functional ansi c compatible compiler. If you are familiar with a C compiler on other operating systems or hardware platforms, you will be able to quickly master GCC. This section describes how to use GCC and some of the most common options for GCC compilers.

Use GCC
The GCC compiler is usually followed by some options and file names. The basic usage of the gcc command is as follows:
Gcc [options] [filenames]
The operation specified by the command line option will be executed on each given file on the command line. The next section describes some of the options you will use most frequently.

GCC options
GCC has more than 100 compilation options available. Many of these options may never be used, but some of the main options will be frequently used. Many GCC options include more than one character. Therefore, you must specify the respective characters for each option, and, just like most Linux commands, you cannot separate the characters with 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 profile information for the prof command during test. c compilation and add the debugging information to the executable file. The second command only tells GCC to create profiling information for the gprof command.

When you do not need any options to compile a program, GCC will create (assuming the compilation is successful) an executable file named a. out. For example, the following command will generate a file named a. out in the current directory:
Gcc test. c
You can use the-o compilation option to specify a file name for the generated executable file instead of a. out. For example, compile a c program named count. C into an executable file named count. You will enter the following command:
Gcc-o count. c

Note: When you use the-o option,-o must be followed by a file name.

GCC also has the compilation option to specify how much the compiler processes. -The c option tells GCC to skip the Assembly and connection steps only by compiling the source code as the target code. This option is frequently used because it makes compilation of multiple C Programs faster and easier to manage. There is a. o extension in the target code file created by GCC.
The-S compilation option tells GCC to stop compilation after an assembly language file is generated for C code. The default extension of assembly language files generated by GCC is. s. The-E Option indicates that the compiler only preprocess the input file. When this option is used, the pre-processor output is sent to the standard output instead of stored in the file.
Optimization Options
When you use GCC to compile C code, it will try to complete the compilation at least and make the compiled code easy to debug. Easy debugging means that the compiled code has the same execution order as the source code, and the compiled code has not been optimized. There are many options that can be used to tell GCC to generate smaller and faster executable files at the expense of more Compilation Time and easier debugging. The most typical options are-O and-O2.
The-O option tells GCC to perform basic optimization on the source code. In most cases, these optimizations make program execution faster. -The O2 option tells GCC to generate code as small as possible and as fast as possible. The-O2 option will make compilation faster than-O. However, code execution is usually faster.
In addition to the-O and-O2 optimization options, there are also some low-level options for generating faster code. These options are very special, and it is best to use them only when you fully understand the effects these options will have on 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 several debugging and profiling options. Among these options, you will most often use the-g and-pg options.
The-g option tells GCC to generate debugging 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. in GCC, you can combine-g with-O (to produce optimization code. This is useful because you can debug your code as close as possible to the final product. When you use both of these options, you must be aware that some of the code you have written 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 additional code to your program. During execution, gprof profiling information is generated to show the time consumption of your program. For more information about gprof, see "gprof.

Debug the GCC program with gdb
Linux contains a GNU debugging program called gdb. Gdb is a powerful debugger used to debug C and C ++ programs. It enables you to observe the internal structure and memory usage of the program while the program is running. The following are some functions provided by gdb:
· It enables you to monitor the value of variables in your program.
· It enables you to set breakpoints so that the program stops running on the specified code line.
· It enables you to execute your code in one line.

Type gdb on the command line and press the Enter key to run gdb. If everything works properly, gdb will be started and you will see similar content on the screen:
GDB is free software and you are welcome to distribute copies of it

Under certain conditions; type "show copying" to see 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)
After you start gdb, you can specify many options on the command line. You can also run gdb in the following ways:
Gdb
When you run gdb in this way, you can directly specify the program to be debugged. This tells gdb to load the executable file named fname. You can also use gdb to check a core file generated due to program termination exceptions, or connect it to a running program. You can refer to the gdb guide or Type gdb-h on the command line to get a simple list of instructions on these options.

Compile the Code for Debugging (Compiling Code for Debugging)
To make gdb work normally, you must make your program contain debugging information during compilation. The debugging information includes the type of each variable in your program, the address ing in the executable file, and the source code line number. Gdb uses this information to associate the source code with the machine code.
Enable the debugging option with the-g option during compilation.

Gdb basic commands
Gdb supports many commands so that you can implement different functions. These commands are loaded from simple files to complex commands that allow you to check the stack content you are calling. Table 27.1 lists some of the commands you will use when debugging with gdb. For details about how to use gdb, refer to the gdb guide page.
Table 27.1. Basic gdb commands.
Command description
File.
Kill to terminate the program being debugged.
List executes a line of source code but does not enter the function.
Next, execute a line of source code but do not enter the function.
Step: execute a line of source code and enter the function.
Run to execute the program currently being debugged
Quit terminate gdb
Watch enables you to monitor the value of a variable, regardless of when it is changed.
Break sets breakpoints in the code, which causes the program to be suspended when it is executed here.
Make enables you to re-generate executable files without exiting gdb.
Shell enables you to run UNIX shell commands without leaving gdb.
Gdb supports many command editing features similar to those of UNIX shell programs. You can press the Tab key like in bash or tcsh to allow gdb to help you complete a unique command. If it is not unique, gdb will list all matching commands. You can also use the mouse key to flip up or down History commands.
Gdb application example
This section uses an example to teach you how to use gdb to debug programs step by step. The program to be debugged is quite simple, but it shows typical applications of gdb.

The programs to be debugged are listed below. This program is called greeting. It displays a simple greeting and 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 ;
String2 [size + 1] = '\ 0 ';
Printf ("The string printed backward is % s \ n", string2 );
}
Compile it with the following command:
Gcc-o test. c
The following results are displayed when the program is executed:
The string is hello there
The string printed backward is
The first line of output is correct, but the output in the second line is not what we expected. The output is as follows:
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. First, enter the following command:
Gdb greeting
Note: Remember to open the debugging option when compiling the greeting program.

If you forget to pass the program to be debugged as a parameter when entering the command to gdb, you can use the file command at the gdb prompt to load it:

(Gdb) file greeting
This command will load the greeting executable file just as you load it in the gdb command line.
You can use the gdb run Command to run greeting. When it is run in gdb, the results will look like this:
(Gdb) run

Starting program:/root/greeting

The string is hello there

The string printed backward is

Program exited with code 041
The output is the same as the running result outside gdb. The problem is, why does reverse printing not work? To find out the crux of the problem, we can set a breakpoint after the for statement of the my_print2 function. The specific method is to enter the list Command three times at the gdb prompt to list the source code:
(Gdb) list

(Gdb) list

(Gdb) list

Tip: Press enter at the gdb prompt to repeat the previous command.

The output of the first 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 will execute the list command again and give the following output:

11 my_print (char * string)

12 {

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

14}

15

16 my_print2 (char * string)

17 {

18 char * string2;

19 int size, I;

20
Press enter again to list the remaining parts of the greeting program:
21 size = strlen (string );

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

23 for (I = 0; I <size; I ++)

24 string2 [size-I] = string;

25 string2 [size + 1] = '\ 0 ';

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

27}
Based on the listed source program, you can see that the place where the breakpoint is to be set is in line 24th. At the gdb command line prompt, type the following command to set the breakpoint:
(Gdb) break 24
Gdb will make the following response:
Breakpoint 1 at 0x139: file greeting. c, line 24

(Gdb)

Enter the run Command to generate the following output:

Starting program:/root/greeting

The string is hello there
Breakpoint 1, my_print2 (string = 0xbfffdc4 "hello there") at greeting. c: 24

24 string2 [size-I] = string
You can set an observation point to observe the value of the string2 [size-I] variable to see how an error is generated by typing:

(Gdb) watch string2 [size-I]
Gdb will respond as follows:
Watchpoint 2: string2 [size-I]
Now we can use the next command to execute the for loop step by step:

(Gdb) next
After the first loop, gdb tells us that the value of string2 [size-I] Is 'H '. Gdb uses the following display to tell you this information:

Watchpoint 2, string2 [size-I]

Old value = 0' \ 000'

New value = 104 'H'

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

23 for (I = 0; I
This value is expected. The results of subsequent cycles are correct. When I = 10, the value of the expression string2 [size-I] is equal to 'E', the value of size-I is equal to 1, and the last character has been copied to the new string.
If you run the loop again, you will see that no value is allocated to string2 [0], and it is the first character of the new string, because the malloc function initializes them as null characters when allocating memory. Therefore, the first character of string2 is a null character. This explains why there is no output when string2 is printed.
It is very easy to correct this error after finding out what the problem is. You have to change the offset of the first character written to string2 in the code to size-1 instead of size. This is because the size of string2 is 12, but the starting offset is 0. The characters in the string are offset 0 to offset 10, and the offset 11 is reserved as null characters.
There are many ways to modify the code properly. One is to set another variable that is 1 smaller than the actual size of the string. This is the code for this solution:
# 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;

String2 [size] = '\ 0 ';

Printf ("The string printed backward is % s \ n", string2 );

}
Other C programming tools
The Slackware Linux release also includes some C development tools that we have not mentioned. This section describes these tools and their typical usage.
Xxgdb
Xxgdb is a graphical interface of gdb Based on the X Window System. Xxgdb includes all the features of gdb in the command line version. Xxgdb allows you to execute Common commands by pressing the button. The place where the breakpoint is set is also displayed in graphs.

You can run the following command in an Xterm window:
Xxgdb
You can use any valid command line options in gdb to initialize xxgdb. In addition, xxgdb has some special command line options, which are listed in Table 27.2.

Table 27.2. xxgdb command line options.
Description
Db_name specifies the name of the debugger used. The default value is gdb.
Db_prompt specifies the debugger prompt. The default value is gdb.
Gdbinit specifies the name of the command file that initializes gdb. The default value is. gdbinit.
Nx tells xxgdb not to execute the. gdbinit file.
Bigicon uses a large icon.
CILS
You can use the following path on the sunsite.unc.edu FTP site:
/Pub/Linux/devel/lang/c/calls.tar. Z
And some earlier Linux CD-ROM releases are also included. Because it is a useful tool, we will introduce it here. If you find it useful, get a copy from BBS, FTP, or another CD-ROM. CILS calls the pre-processor of GCC to process the given source program files, and then outputs the function call tree in these files.
Note: After you log on to your system as a Super User, perform the following steps: 1. decompress the files and untar files. 2. The sub-directory created after the cd enters calluntar. 3. Move the file named CILS to the/usr/bin directory. 4. Move the file named calls.1 to the/usr/man/man1. 5. Delete the/tmp/CILS directory. These steps will install the CILS program and its Guide page on your system.

When the call trace result is printed by CILS, the file name of the file where the function is located is given in brackets after the function:
Main [test. c]
If the function is not in the file provided to CILS, and does not know where the called function comes from, only the function name is displayed:
Printf
CILS does not output recursive or static functions. Recursive functions are shown as follows:
Fact <recursive in factorial. c>
Static functions are shown as follows:
Total [static in calculate. c]
As an example, we assume that the following program is processed with cballs:

# 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;

String2 [size] = '\ 0 ';

Printf ("The string printed backward is % s \ n", string2 );

}
The following output is generated:
1 main [test. c]

2 my_print [test. c]

3 printf

4 my_print2 [test. c]

5 strlen

6 malloc

7 printf
CILS has many command line options to set different output formats. For more information about these options, see the CILS guide. The method is to type call-h on the command line.
Cproto
Cproto reads the C source code file and automatically generates a prototype Declaration for each function. Cproto can save you a lot of time to define the function prototype when writing a program.
If you want 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;

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 an inclusion file that defines the function prototype.
Indent
The indent utility is another programming utility included in Linux. In short, this tool produces beautiful indent formats for your code. Indent also has many options to specify how to format your source code. For more information about these options, see the indent guide and enter indent-h on the command line.

The following example shows the default output of indent:
Run the C code before 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;

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;

String2 [size] = '\ 0 ';

Printf ("The string printed backward is % s \ n", string2 );

}
Indent does not change the actual content of the code, but just changes the appearance of the Code. It is always a good thing to make it more readable.
Gprof
Gprof is a program installed in the/usr/bin directory of your Linux system. It allows you to analyze your program to know which part of the program is most time-consuming during execution.
Gprof will tell you the number of calls to each function in the program and the percentage of time each function is executed. This information is useful if you want to improve the performance of your program.
To use gprof in your program, you must add the-pg option when compiling the program. This will make the program generate a file named gmon. out during each execution. Gprof uses this file to generate profiling information.
After you run your program and generate the gmon. out file, you can use the following command to obtain the profiling information:
Gprof
The program_name parameter is the name of the program that generates the gmon. out file.
Tip: gprof generates a large amount of profiling data. If you want to check the data, you 'd better redirect the output to a file.
F2c and p2c
F2c and p2c are two source code conversion programs. F2c converts FORTRAN code to C code, and p2c converts Pascal code to C code. These two programs will be installed when you install GCC.
If you have code written in FORTRAN or Pascal that needs to be rewritten in C, f2c and p2c are very useful to you. The C code generated by these two programs can be directly compiled by GCC without modification.
If the FORTRAN or Pascal program to be converted is small, you can directly use f2c or p2c without any options. If the program to be converted is large and contains many files, you may need to use some command line options.
Run f2c on a FORTRAN program and run the following command:
F2c my_fortranprog.f

Note: f2c requires that the program to be converted have an extension of. f or a. F.

To replace a Pascal program with a C program, enter the following command:
P2c my_pascalprogram.pas
The names of the C source code generated by these two programs are the same as those of the original file, 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.