Introduction to GCC applications in Linux

Source: Internet
Author: User

When developing applications for Linux, the C language is used in most cases. Therefore, almost every Linux programmer is faced with the primary issue of flexible use of the C compiler. Currently, the most common C language compiler in Linux is GCC (GNU Compiler Collection), which is a compilation system that complies with the ansi c standard in the GNU project, compile programs written in C, C ++, Object C, and other languages. Not only is GCC very powerful, but its structure is also extremely flexible. One of the most commendable points is that it can support a variety of languages through different front-end modules, such as Java, Fortran, Pascal, Modula-3 and Ada.

Openness, freedom, and flexibility are the charm of Linux, and this is reflected in the GCC through which programmers can better control the entire compilation process. When using GCC to compile a program, the compilation process can be divided into four stages:

◆ Pre-processing)

◆ Compile (Compiling)

◆ Assembly)

◆ Link (linking)

Linux programmers can end GCC at any stage of compilation according to their own needs, so as to check or use the output information of the compiler at this stage, or control the final binary file, so that you can prepare for future debugging by adding different numbers and types of debugging code. Like other commonly used compilers, GCC also provides flexible and powerful code optimization functions to generate code with higher execution efficiency.

GCC provides more than 30 warning messages and three warning levels to help enhance program stability and portability. In addition, GCC has made a lot of extensions to the Standard C and C ++ languages, which improves program execution efficiency, helps the compiler to optimize code, and reduces programming workload.

Starting with GCC

Before learning to use GCC, the following example can help users quickly understand the working principle of GCC and apply it to actual project development. First, enter the code shown in Listing 1 in a familiar Editor:

Listing 1: Hello. c

 


      #include int main(void){printf ("Hello world, Linux programming!//n");return 0;}

Run the following command to compile and run the program:

 


      # gcc hello.c -o hello# ./helloHello world, Linux programming!

From the programmer's point of view, you only need to simply execute a GCC command, but from the compiler's point of view, you need to complete a series of very complicated work. First, GCC needs to call the Preprocessing Program CPP, which is responsible for expanding the macro defined in the source file, and inserting the content contained in the "# include" statement into it; then, GCC will call CCL and as to compile the processed source code into the target code. Finally, GCC will call the link program LD to link the generated target code into an executable program.

To better understand the working process of GCC, you can separate the above compilation process into several steps and observe the running results of each step. The first step is to pre-compile. The-e parameter allows GCC to stop the compilation process after preprocessing:

 


      # gcc -E hello.c -o hello.i

If you check the content in the hello. cpp file, you will find that the content of stdio. H is indeed inserted into the file, and other macro definitions that should be preprocessed are also processed accordingly. The next step is to compile hello. I as the target code, which can be done by using the-C parameter:

 


      # gcc -c hello.i -o hello.o

By default. the I file is considered as the C language source code after preprocessing. Therefore, the above command will automatically skip the preprocessing step and start the compilation process. You can also use the-x parameter to let GCC compile from the specified step. The last step is to link the generated target file to an executable file:

 


      # gcc hello.o -o hello

 

When the modular design is used for software development, the entire program is usually composed of multiple source files, and multiple compilation units are formed accordingly, using GCC can well manage these compilation units. Suppose there is a program consisting of two source files foo1.c and foo2.c. to compile them and generate the executable program Foo, you can use the following command:

 


      # gcc foo1.c foo2.c -o foo

If more than one file is processed at the same time, GCC will continue to follow the preprocessing, compilation, and link processes. If we look into it, the above command is roughly equivalent to executing the following three commands in sequence:

 


      # gcc -c foo1.c -o foo1.o# gcc -c foo2.c -o foo2.o# gcc foo1.o foo2.o -o foo

It is a waste of time to compile a project that contains many source files using only one GCC command. Suppose there are 100 source files in the project that need to be compiled, and each source file contains 10000 lines of code. If you use only one GCC command as above to complete the compilation, then GCC needs to re-compile each source file and then connect all the files. Obviously, this wastes a lot of time, especially when a user modifies only one of the files, there is no need to re-compile each file, because many generated target files will not change. To solve this problem, the key is to use GCC flexibly and use tools like make.

Warning function

GCC provides complete error check and warning functions to help Linux programmers write more professional and elegant code. First, read the program shown in Listing 2. The code is poorly written. It is not difficult to pick out a lot of problems after a careful check:

◆ The return value of the main function is declared as void, but it should be int;

◆ The GNU syntax extension is used to declare 64-bit integers using long, which does not comply with the ANSI/iso c language standard;

◆ The main function does not call the return statement before termination.

Listing 2: illcode. c

 


      #include void main(void){long long int var = 1;printf("It is not standard C code!//n");}

Next let's take a look at how GCC helps programmers find these errors. When GCC compiles source code that does not conform to the ANSI/iso c language standards, if the-pedantic option is added, a warning message is generated when the extended syntax is used:

 


      # gcc -pedantic illcode.c -o illcodeillcode.c: In function `main':illcode.c:9: ISO C89 does not support `long long'illcode.c:8: return type of `main' is not `int'

Note that the-pedantic compilation option does not guarantee full compatibility between the compiled program and the ANSI/iso c standard. It can only be used to help Linux programmers get closer and closer to this goal. In other words, the-pedantic option can help programmers find some codes that do not conform to the ANSI/iso c standard, but not all of them, in fact, only those situations that require compiler diagnosis in the ANSI/iso c language standards can be detected and warned by GCC.

In addition to-pedantic, GCC also has some other compilation options that can generate useful warning information. Most of these options start with-W, the most valuable of which is "number-wall". Using this option enables GCC to generate as many warning messages as possible:

 


      # gcc -Wall illcode.c -o illcodeillcode.c:8: warning: return type of `main' is not `int'illcode.c: In function `main':illcode.c:9: warning: unused variable `var'

Although the warning information given by GCC cannot be regarded as an error in a strict sense, it is likely to become a place where errors occur. A good Linux programmer should try to avoid warning information so that his code is always concise, elegant, and robust.

In terms of warning handling, another common compilation option is-werror, which requires GCC to treat all warnings as errors, which is using automatic compilation tools (such as make) is very useful. If the-werror option is included during compilation, GCC stops compilation where warnings are generated, forcing programmers to modify their own code. The compilation process can be pushed forward only when the corresponding warning information is cleared. The execution is as follows:

 


      # gcc -Wall -Werror illcode.c -o illcodecc1: warnings being treated as errorsillcode.c:8: warning: return type of `main' is not `int'illcode.c: In function `main':illcode.c:9: warning: unused variable `var'

For Linux programmers, the warning messages provided by GCC are very valuable. They not only help programmers write more robust programs, but also provide powerful tools for tracking and debugging programs. We recommend that you always use the-wall option when compiling source code with GCC, and gradually cultivate it into a habit, which is helpful for identifying common implicit programming errors.

Library dependency

It is rare to develop software in Linux without using third-party function libraries. Generally, one or more function libraries must be supported to complete the corresponding functions. From the programmer's perspective, the function library is actually a collection of header files (. h) and library files (. So or.. Although most functions in Linux place header files in the/usr/include/directory by default, and the library files in the/usr/lib/directory, but not all cases are like this. For this reason, GCC must have its own way to find the required header files and library files during compilation.

GCC uses the Directory Search method to find the required files. The-I option can add a new directory to the GCC header file search path. For example, if there is a header file required for compilation in the/home/xiaowp/include/directory, you can use the-I option to make GCC find them smoothly:

 


      # gcc foo.c -I /home/xiaowp/include -o foo

Similarly, if you use a library file that is not in the standard location, you can use the-L option to add a new directory to the GCC library file search path. For example, if there is a link to the library file libfoo. So in the/home/xiaowp/lib/directory, you can use the following command to make GCC find it smoothly:

 


      # gcc foo.c -L /home/xiaowp/lib -lfoo -o foo

It is worth explaining that the-L option instructs GCC to connect to the library file libfoo. So. The naming conventions for library files in Linux are as follows: it should start with three letters of Lib. Because all library files follow the same rules, therefore, when you use the-L option to specify the name of the Linked Library file, you can save lib with three letters. That is to say, when GCC processes-lfoo, it automatically links to libfoo. so file.

Library files in Linux are divided into two categories. so) and static link library (usually. end A), the difference between the two is only that the Code required for program execution is dynamically loaded at runtime, or static load at compilation. By default, GCC preferentially uses the dynamic link library when linking. Static Link Library is considered only when the dynamic link library does not exist. If necessary, you can add the-static option during compilation, use a static Link Library. For example, if there is a link in the/home/xiaowp/lib/directory, the library file libfoo is required. so and libfoo. a. To enable GCC to only use the static link library when linking, run the following command:

 


      # gcc foo.c -L /home/xiaowp/lib -static -lfoo -o foo

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.