LINUX C language programming basics

xiaoxiao2021-03-05  28

LINUX C language programming basics

1. Compilation of the source program

In Linux, if you want to compile a C language source, we should use the GNU GCC compiler. Below we will explain how to use the GCC compiler with an instance.

Suppose we have a very simple source program (Hello.c):

INT main (int Argc, char ** argv)

{

Printf ("Hello Linux / N");

}

To compile this program, we only need to execute them under the command:

GCC -O Hello Hello.c

The GCC compiler will generate a Hello executable file. Execute ./hello can see the output result of the program. The gcc in the command line means that we use GCC to compile our source programs, and the -o option means us Requires the compiler to the executable file of our output is Hello and Hello.c is our source program file.

There are many options in the GCC compiler. Generally, we just know how many of them are enough. The -o option We already know, indicating that we ask the executable file name. -c option means that we only require the compiler to output the target Code, without having to output executable files. The -g option means that we ask the compiler to provide us for debugging the program when compiling.

I know these three options, we can compile the simple source of our yourself, if you want to know more options, you can view the GCC's help document, there are many detailed instructions for other options.

2. Makefile

Suppose we have a program below, the source code is as follows:

/ * main.c * /

#include "mytool1.h"

#include "mytool2.h"

INT main (int Argc, char ** argv)

{

MyTool1_print ("Hello");

MyTool2_print ("Hello");

}

/ * MyTool1.h * /

#ifndef _mytool_1_h

#define_mytool_1_h

Void mytool1_print (char * print_str);

#ENDIF

/ * MyTool1.c * /

#include "mytool1.h"

Void mytool1_print (char * print_str)

{

Printf ("this is mytool1 print% s / n", print_str);

}

/ * mytool2.h * /

#ifndef _mytool_2_h

#define _mytool_2_h

Void mytool2_print (char * print_str);

#ENDIF

/ * MyTool2.c * /

#include "mytool2.h"

Void mytool2_print (char * print_str)

{

Printf ("this is mytool2 print% s / n", print_str);

}

Of course, because this program is very short, we can compile this way.

gcc -c main.c

gcc -c mytool1.c

gcc -c mytool2.c

GCC -O main main.o mytool1.o mytool2.o

In this way, we can also generate the main program, and it is very troublesome from time to time. But if we think that if one day we have modified one of them (such as MyTool1.c), then we need to re-enter the command? Maybe you Will say, this is easy to solve, I wrote a shell script, let her help me do it. Yes, for this program, it can play a role. But when we think about things more complicated One point, if our procedure has hundreds of source programs, is it necessary to compile the compiler to compile?

To this end, smart programmers came up with a good tool to do this, this is make. We can solve the above problem before we perform Make, we must first Write a very important file. - Makefile. For the program above, a possible Makefile file is:

# This is the Makefile file main: main.o mytool1.o mytool2.o

GCC -O main main.o mytool1.o mytool2.o

Main.o: main.c mytool1.h mytool2.h

gcc -c main.c

Mytool1.o: mytool1.c mytool1.h

gcc -c mytool1.c

Mytool2.o: mytool2.c mytool2.h

gcc -c mytool2.c

With this makefile file, when will we modify what files in the source program, we only need to execute the make command, our compiler will only compile the files related to our modified files, and other files do not want to connect. Deal with.

Let's learn how made makefile is written.

In the Makefile, the rows that start are notes. The most important thing in Makefile is a description of the dependency of the description file. The general format is:

Target: Components

Tab Rule

The first line represents the dependency. The second line is the rule.

For example, the second line of the Makefile file above

Main: main.o mytool1.o mytool2.o

Indicates that our target (Components) is Main.o mytool1.o mytool2.o When you rely on object modified after the target modification, you will go to the command specified by the rules. Just like our The Makefile's third line is said to execute gcc -o main main.o mytool1.o mytool2.o pay attention to the Tab in the rules, and it is a Tab key.

Makefile has three very useful variables. The meaning of $ @, $ ^, $

$ @ - Target file, $ ^ - All dependencies, $ <- the first dependency file.

If we use the above three variables, then we can simplify our Makefile file as:

# This is a simplified Makefile

Main: main.o mytool1.o mytool2.o

GCC -O $ @ $ ^

Main.o: main.c mytool1.h mytool2.h

GCC-C $

Mytool1.o: mytool1.c mytool1.h

GCC-C $

Mytool2.o: mytool2.c mytool2.h

GCC-C $

After a simplification, our makefile is simple, but people sometimes think simple. Here we learn a Makefile's default rules.

.c.o:

GCC-C $

This rule indicates that all .o files are dependent on the corresponding .C file. For example, MyTool.o depends on MyTool.c, Makefile can also become:

# This is another simplified Makefile

Main: main.o mytool1.o mytool2.o

GCC -O $ @ $ ^

.c.o:

GCC-C $

Ok, our makefile is almost the same, if you want to know more about the Makefile rule, you can view the appropriate documentation.

3. Link of library library

Try to compile the following procedure

/ * TEMP.C * /

#include

INT main (int Argc, char ** argv)

{

Double Value;

Printf ("Value

f / n ", value);

}

This program is quite simple, but when we compile with gcc -o temp temp.c, the following is shown.

/TMP/cc33kydu.o: in function `main:

/TMP/cc33kydu.o(.Text 0xe): undefined Reference to `log

Collect2: ld returned 1 exit status

This error is because the compiler can not find the specific implementation of the log. Although we include the correct header file, we still have to connect the determined library when compiling. Under Linux, in order to use mathematical functions, we must use mathematics Library connection, to this, we have to join the -LM option. Gcc -o temp temp.c -lm can be able to compile correctly. Maybe someone wants to ask, how can we connect to the library when we use the printf function? Yes, this is like this, For some common functions, the GCC compiler will automatically connect to some common libraries so that we don't have to specify themselves. Sometimes we want to specify the path of the library when compiling the program, this time we want to use The compiler's -l option specifies the path. For example, we have a library under / home / hoyt / mylib, so we have to add -l / home / hoyt / mylib when we compile. For some standard libraries, we There is no need to point out the path. As long as they can get a default library, it is possible. The path of the system's default library / lib / usr / lib / usr / local / lib is in these three paths, we can not Specify path. There is also a problem, sometimes we use a function, but we don't know the name of the library, what should I do this time? I am sorry, I don't know the answer for this question, I only have a stupid approach. First I went to the standard library path to find a look at the library with the function I use, I found a libctor file (libpthread.a). Of course, if I can't find it, there is only one Stupid method. For example, I have to find the library of SIN. I have to use nm -o /lib/*.so|Grep sin> ~ / sin command, then look at ~ / sin file, go to it. I have been looking. In the SIN file, I will find such a line of rings, linem-2.1.2.so:00009fa0 w sin, I will know that SiN is in the libm-2.1.2.so library, I can use the -lm option (removed front) LIB and later version logo, there is still M. So is -LM). If you know how to find it, please tell me quickly, I am very grateful. Thank you!

4. Debugging the program

The procedures we have written are unlikely to succeed. In our program, there will be many mistakes we can't think of, this time we have to debug our procedures.

The most commonly used debugging software is GDB. If you want to debug programs in the graphical interface, you can now choose XXGDB. Remember to join the -g option when compiling. About GDB's use can look at GDB help files. Because I don't have I used this software, so I can't say how to use. But I don't like to use GDB. Tracking a program is very annoying, I usually use the value of the intermediate variable in the program to debug the program. Of course you can Choosing your own way, there is no need to learn others. Now there is a lot of IDE environments, which have been bringing a debugger yourself. You can choose a few tricks to find out what you like.

5. Head file and system for help

Sometimes we only know the general form of a function, don't remember the exact expression, or don't remember that the function is described in that header file. At this time we can help the system.

For example, we want to know the exact form of the FREAD function, and we will export a detailed explanation of a function. The header file in which the function is located. If we want to write this function, when we execute When Man Write, the result of the output is not what we need. Because we want the Write this function, it is a description of the command of Write. In order to get the Write function, we have to use Man 2 Write. 2 It means that the WRITE function we use is the system call function, and there is a library function we use 3 indicating that the function is C.

Remember when, MAN is our best assistant.

____________________________________ ===================================== Help others, happy!

LINUX C language programming

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 C

GNU C compiler

Use GDB to debug GCC application

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).

-------------------------------------------------- ------------------------------

Note: The PRETTY Print Programs automatically helps you format the source code to generate a consistent indentation format.

-------------------------------------------------- ------------------------------

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. The language is written. From then, C will become the most widely used computer language in the world.

C can be found in the programming field:

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 program 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.c

GCC -PG Test.c

The first command tells the GCC to establish a profile information for the PROF command and add the debug information to the executable file when compiling Test.c. The second command only tells the GCC to establish a profiling information for the gprof command.

When you don't have to 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.

-------------------------------------------------- ------------------------------

The GCC also has the compilation options for specifying the compiler processing. The -c option tells the GCC to step only to compile the source code as the target code. This option is very frequent because it makes compiling multiple C procedures Faster and easier to manage. The target code file established by the default when the GCC has an 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. What is the compiled code? 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 option. -G Option tells 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 tells GCC to add additional code in your program, generate GPROF to display the time consumption of your program. For more information on GPROF, please refer to the "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 variables in your program.

It allows you to set breakpoints to stop execution on the specified code line.

It makes you execute your code in a line.

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 well to distributes of itunder ceerts; 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.

Compilant 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.

Description of the command

File loads the executable you want to debug.

Kill terminates the program being debugging.

List lists a part of the source code that generates execution files.

NEXT executes a source code but does not enter the inside of the function.

STEP performs a row source code and enters the inside of the function.

Run executes the current debugged program

Quit termination GDB

Watch allows you to monitor the value of a variable regardless of whether it is changed.

Break sets breakpoints in the code, which will hang it when the program is executed here.

Make allows you to re-generate executables without exiting GDB.

The shell allows you to execute the 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 debugged program is quite simple, but it shows the typical application of GDB.

The program that will be debugged is listed. This program is called Greeting, which shows 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% s

", string);

}

Void my_print2 (char * string)

{

Char * string2;

Int size, i;

SIZE = Strlen (String);

String2 = (char *) Malloc (SIZE 1);

For (i = 0; i

String2 [size - i] = string [i]; string2 [size 1] = "

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

New Post(0)