LINUX C language programming

xiaoxiao2021-03-06  42

Original: rick mcmullin

Foreword

There is a lot of software development tools in Linux issues. Many of them are developed for C and C applications. This article describes tools that can be used for C applications and commissioning under Linux. The main purpose of this article is to introduce How to use C compiler and other C programming tools under Linux, not C language programming tutorial. In this article, you will learn the following knowledge:

What is a C GNU C compiler with GDB to debug GCC applications

You can also see other useful C programming tools issued with Linux. These tools include Pretty Print Programs, additional debugging tools, function prototype automatic buildings (Automatic Function Prototypers).

What is C?

C is a widely used universal programming language in the early days of the UNIX operating system. It was first written by Dennis Ritchie, Bell Lab, for UNIX-assisted development, and UNIX is a compilation language and a called B. Language is written. From then on, C has become the most widely used computer language in the world. C can be used in the field of programming, there is some of the following:

It is a very common language. Almost you can think of at least one C compiler on the computer. And its syntax and function library are unified on different platforms, this Features are very attractive to developers. The speed of writing written with C is very fast. C is a system language on all versions of UNIX.

C has developed greatly in the past twentieth year. A C language standard called ANSI C is released in the US National Standards Institute in the late 1980s. This is more guaranteed in different platforms in different platforms. The consistency of C. In the 1980s, a C . C will also be described in another article "C Programming" in another article.

The C compiler available on Linux is a GNU C compiler, which is based on the programming license of the Free Software Foundation, so you can freely release it. You can find it on Linux's distribution discs.

GNU C compiler

The GNU C compiler (GCC) issued with Slackware Linux is a full-featured ANSI C compatible compiler. If you are familiar with a C compiler on other operating systems or hardware platforms, you will be able to master GCC. This The section will show you how to use the GCC and some of the most common options for some GCC compilers.

Use GCC

Typically followed by some options and file names using the GCC compiler. 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 the file on the command line. The next section will narrate some of the option you will use.

GCC option

GCC has more than 100 compilation options available. Many of these options you may never use, but some main options will be used frequently. Many of the GCC options include more than one character. So you must be The option specifies its respective hyphens, just like most Linux commands, you cannot follow a set of options after a single hyphen. For example, the following two commands are different:

GCC -P -G Test.cgcc -pg test.c

The first command tells the GCC to compile Test.c, set the profile information and add the debug information to the executable file. The second command only tells the GCC to establish a profiling information for the gprof command. When you don't have any When you compile a program, GCC will establish (assuming compile success) a executable name called A.out. For example, the following command will generate a file called 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, for example, compile a C program called Count.c as a executable called count, you will enter the following The command:

GCC -O count country.c

Note: When you use the -o option, the -o must follow a file name .GCC also has the compilation options for specifying the compiler processing. -C Option tells GCC only to compile the source code as a target code to skip assembly and connect Step. This option is very frequently used because it makes it easier when compiling multiple C procedures, and it is more likely to manage. The target code file established by the GCC is available in the default .o extension.

The -s compilation option tells the GCC to stop compilation language files after the C code is generated. The default extension of the assembly language file generated by the GCC is the .s. -E option indicates that the compiler is only preprocessing the input file. When this When the option is used, the output of the preprocessor is sent to the standard output instead of being stored in the file.

Optimization option

When you use GCC to compile C code, it will try to complete compilation with the least amount of time and make the compiled code easy to debug. Easy to debug means that the compiled code is the same as the source code, and the compiled code has not been passed. Optimization. There are many options that can be used to tell GCC to generate smaller and faster executables on the basis of more compile time and sacrificial easily. These options are -O and -O2 options.

The -o option tells GCC to optimize the source code. These optimizations will make the program execute faster in most cases. -O2 option tells GCC to generate as small and as fast as possible. -O2 option will make compilation The speed is slower than using -O. But the usual code execution speed will be faster.

In addition to the -O and -O2 optimization options, there are some low-level options to generate faster code. These options are very special, and it is best to only be completely understood by these options. The effect is used again. For a detailed description of these options, please refer to the GCC's Guide page, type the Man GCC on the command line.

Debug and parsing options

GCC supports several commissioning and profiling options. In these options you will use the -g and -pg options. -G Option tells the GCC to generate debugging information that can be used by the GNU debugger to debug your program. GCC There is no feature in a lot of other C compilers, you can use -g and -o (generated optimized code) in GCC. This is very useful because you can debug you as close as possible as possible. Code. When you use these two options simultaneously, you must know that some code you wrote is already modified by GCC. For more information on debugging the C program, please see the next section "Debugging with GDB C Program ". -Pg Option Tell GCC to add additional code in your program, generate gprof to display profiling information to display your program. For more information on GPROF, please refer to" GPROF "section .

Debug GCC program with GDB

Linux includes 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 at runtime. The following is GDB provided Some features:

It allows you to monitor the value of the variables in your program. It allows you to set breakpoints to stop executing on the specified code line. It allows you to perform your code.

Type GDB on the command line and press Enter to run GDB, if everything is normal, 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 itunder 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)

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

GDB

When you run GDB in this way, you can specify the program you want to debug. This will tell GDB to load an executable file named FNAME. You can also use GDB to check an Core file that is generated due to an exception termination Or connect with 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. To debug code for debugging

In order to make GDB work properly, you must make your program contain debugging information when compiling. Debug information contains the type of each variable in your program and the address map in the executable, and the line number of the source code. GDB uses these The information is associated with the source code and the machine code.

Turn on the debug option with the -g option when compiling.

GDB basic order

GDB supports a lot of commands to enable you to achieve different features. These commands are loaded from simple files to the complex commands that allow you to check the contents called the stack content. Table 27.1 lists some of you will use when using GDB debugging Command. Want to know the details of GDB, please refer to the GDB guide page.

Table 27.1. Basic GDB Command.

The command describes the executable file that File is loaded. Kill terminates the program that is debugging. List lists a part of the source code generating the execution file. NexT executes a row source code but does not enter the function of the function. Step execute a row source code And enter the function inside .Run executes the current debugged program Quit Termination GDBWATCH allows you to monitor the value of a variable, regardless of whether it is changed. Break sets breakpoints in the code, which will make the program to be executed here .make allows you to re-generate the executable file without exiting GDB. SHELL allows you to execute a UNIX shell command without leaving GDB.

GDB supports a lot of command editing features like UNIX shell programs. You can press the Tab key like it in Bash or TCSH to let GDB help you make up a unique command. If you don't have unique, GDB will list all match commands. You You can also flip history commands with cursor keys.

GDB application example

This section teaches you step by step by step. The program is quite simple, but it shows the typical application of GDB. The program will be debugged. This program is called Greeting, it Show a simple greeting and listed it in the back sequence.

#include main () {char my_string [] = "hello there"; my_print (my_string); my_print2 (my_string);} void my_print (char * string) {printf ("the string is% SN", String);} void my_print2 (char * string) {char * string2; int size, i; size = strlen (string); string2 = (char *) malloc (size 1); for (i = 0; i

Compile it with the following command:

GCC -O Test Test.c

The following results displayed when this program is executed:

The string is hello thererethe stringprinted backward is

The first line of output is correct, but the second line of printing is not what we expect. The output we have envisage should be:

The String Printed Backward Is Ereht Olleh

For some reason, my_print2 functions do not work properly. Let us use GDB to see where there is, type the following command:

GDB GRETING

Note: Remember to open the debug option when compiling the Greeting program.

If you forget to pass the program you want to debug as a parameter, you can load it with the file command under the GDB prompt:

(GDB) File Greeting

This command will load the Greeting executable is like you to load it in the GDB command line.

At this time, you can run Greeting with GDB's Run command. When it is running in GDB, the result will be like this:

(GDB) Runstarting Program: / Root / GreetingThe String is Hello Therethe String Printed Backward Isprogram EXITED with CODE 041

This output is the same as the result of running outside GDB. The problem is, why don't you work in the reverse order? In order to find the crux, we can set a breakpoint after the FOR statement of my_print2 function, the specific practice is in the GDB prompt. Type the list command three times, list the source code:

(GDB) List (GDB) List (GDB) LIST

Tip: Press Enter to return to the car at the GDB prompt.

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

1 #include 23 main () 4 {5 char my_string [] = "hello there"; 67 my_print (my_string); 8 my_print2 (my_string); 9} 10

If you press Enter, GDB will execute a list command, give the following output:

11 my_print (char * string) 12 {13 Printf ("THE STRING IS% SN", String); 14} 1516 my_print2 (char * string) 17 {18 char * string2; 19 int size, i; 20

Pressing a cycle will list the remaining parts of the Greeting program:

21 size = strlen (String); 22 string2 = (char *) Malloc (size 1); 23 for (i = 0; i

Based on the source program listed, you can see where you want to break points on line 24, type the following command to set breakpoints under the GDB command line prompt:

(GDB) BREAK 24

GDB will make the following response:

Breakpoint 1 AT 0x139: File Greeting.c, Line 24 (GDB)

Now type the RUN command, will generate the following output:

Starting program: / rootingthe string is hello therebreakpoint 1, my_print2 (string = 0xbffdc4 "hello there") at Greeting.c: 2424 string2 [size-i] = string [i]

You can see how the error is generated by setting an observation point of the value of the string2 [size - i] variable, the practice is to type:

(gdb) Watch string2 [size - i]

GDB will make the following response:

WatchPoint 2: String2 [size - i]

Now you can use the next command to perform the for loop for a step:

(GDB) Next

After the first cycle, GDB tells us that the value of string2 [size - i] is `h` GDB tells you this information with the following display:

WatchPoint 2, string2 [size - i] old value = 0 `00'myEw value = 104` H'my_print2 (string = 0xbffdc4 "hello there") at Greeting.c: 2323 for (i = 0; i

This value is expected. The result of the later several cycles is correct. When i = 10, the value of expression string2 [size - i] is equal to the value of `E`, size - i is equal to 1, the last one The characters have been copied to the new stroke.

If you do 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 initials them into empty (null) characters when allocating memory So the first character of String2 is empty. This explains why there is no output when printing string2.

Now find out where the problem is, correct this error is very easy. You have to change the shift of the first character in String2 in the code to Size - 1 instead of size. This is because String2 size 12, but the start offset is 0, the characters in the string from the offset 0 to the offset 10, the offset amount 11 is a null character.

In order to make the code work properly, there are many modifications. One is a variable that sets another actual size of the string. This is the code of 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% SN", String );} my_print2 {char * string2; int size, size2, i; size = strlish (string); size2 = size -1; string2 = (char *) malloc (size 1); for (i = 0; i

Another C programming tool

Slackware Linux also includes some C development tools we have not mentioned. This section will introduce these tools and their typical usage.

xxgdb

XXGDB is a XXGDB-based graphical interface. XXGDB includes all features on the gdb of the command line. XXGDB enables you to perform a commonly used command by pressing the button. Place the breakpoint is also displayed. You can use the commands below in an XTERM window to run it:

xxgdb

You can initialize XXGDB with any valid command line option in GDB. In addition, XXGDB also has some unique command line options, and these options are listed in Table 27.2. Xxgdb command line options.

Select DB_NAME to specify the name of the debugger used, the default is GDB.DB_PROMPT Specify the debugger prompt, default to the file name of the command file of the initialization GDB.Gdbinit, default is .gdbinit. NX tells xxgdb Execute the .gdbinit file. Bigicon uses the big icon .calls

You can use the following path in the Sunsite.Unc.edu FTP site:

/Pub/linux/devel/lang/calls.tar.z

To get Calls, some old version of the Linux CD-ROM release is also included. Because it is a useful tool, we also introduce here. If you think useful, from BBS, FTP, or another CD -ROM Lote. Calls Calls the GCC's preprocessor to process the given source program file, then output the function call the tree in these files.

Note: Install Calls on your system, perform the following steps after you log in as yours: 1. Unzip and Untar files. 2. The CD enters the subdirectory established after Calls Untar. 3. Move the name called Calls to / usr / bin directory. 4. Move the file called calls.1 to the directory / usr / man / man1. 5. Delete the / tmp / calls directory. These steps will load your calls and its guide page to load your System on the system.

When Calls prints a tracking result, it gives the file name of the file in the function behind the function after the function:

Main [Test.c]

If the function is not in the file given to the calls, calls don't know where the call is called, only the name of the function is displayed:

PRINTF

Calls does not output the recursive and static function. The recursive function is displayed below:

FACT <<< Recursive in Factorial.c >>>

Static function is like this:

Total [static in caverculate.c]

As an example, assume that the following programs are treated with Calls:

#include main () {char my_string [] = "hello there"; my_print (my_string); my_print2 (my_string);} my_print (char * string) {printf ("THE STRING IS% SN", String );} my_print2 {char * string2; int size, size2, i; size = strlish (string); size2 = size -1; string2 = (char *) malloc (size 1); for (i = 0; i

The following output will be produced:

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 lot of command line options to set different output formats, please refer to the Calls guide page for more information on these options. Method is to type Calls -h on the command line.

CPROTO

CPROTO reads into the C source file and automatically generates prototypes for each function. With CPROTO, you can save you a lot of time to define a function prototype when writing programs. If you let Cproto processes the following code: #include main () {char my_string [] = "hello there"; my_print (my_string); my_print2;} my_print (char * string) {printf ("the string is% SN", * 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

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 defined function prototype.

Indent

The Indent utility is another programming utility included in Linux. This tool simply produces a beautiful indentation format for your code. Indenter has many options to specify how to format your source code. These options For more information, please see the Indenter page, type it on the command line.

The following example is the default output of Indent:

Run the previous C code before:

#include main () {char my_string [] = "hello there"; my_print (my_string); my_print2 (my_String);} my_print (char * string) {printf ("the string is% sn", * String);} my_print2 (char * string) {char * string2; int size, size2, i; size = strlish (string); size2 = size -1; string2 = (char *) Malloc (size 1); for (SIZE 1); i = 0; I

Code running in Indent:

#include main () {char my_string [] = "hello there"; my_print (my_string); my_print2 (my_String);} my_print (char * string) {printf ("the string is% sn", * String);} my_print2 (char * string) {char * string2; int size, size2, i; size = strlish (string); size2 = size -1; string2 = (char *) Malloc (size 1); for (SIZE 1); i = 0; i

GPROF

GPROF is a program installed in the / usr / bin directory of your Linux system. It makes you analyzing your program to know which part of the program is performed.

GPROF will tell you the number of times each function called and the time to perform time when performing each function. If you want to improve your program performance, this information is very useful.

In order to use GPROF on your program, you must add -pg options when compiling. This will cause the program to generate a file called GMon.out when executed. Gprof generates a profiling information with this file.

After you run your program and generate the gmon.out file, you can use the following command to obtain an analysis:

GPROF

The parameter program_name is the name of the program that produces the GMON.out file.

Tip: The profiling data generated by GPROF is very large. If you want to check this data, it is best to redirect the output to a file.

F2C and P2C

F2C and P2C are two source code conversion programs. The F2C converts the Fortran code to C code, and P2C converts the PASCAL code to C code. When you install GCC, both programs will be installed.

If you have some code written by Fortran or Pascal, F2C and P2C are very useful to you with C. The C code generated by the two programs is generally compiled by GCC without modification.

If the Fortran or PASCAL program to be converted is smaller, you can use the F2C or P2C without any options. If you want to convert the program, you can use a lot of files, you may have to use some command line options.

Use F2C on a Fortran program, enter the following command:

F2C my_fortranprog.f

Note: The extension of the F2C requiring the converted program is .f or a .f.

To replace a PASCAL program as a C program, enter the following command:

P2C my_pascalprogram.pas

The file names of these two programs generated by C source code are the same as the original file name, but the extension is changed to .f or .pas.

转载请注明原文地址:https://www.9cbs.com/read-62956.html

New Post(0)