Compile C Programs in Linux

Source: Internet
Author: User
GCC is no longer a small C program mainly for the GNU project's own software.
Language compiler. Today, it supports many different languages, including
C, C ++, Ada, Fortran, Objective C, and even Java. In fact, modern Linux
In addition to being proud to show off those
In addition to languages directly supported by the tool, it also supports a large number of other languages. Increasingly popular scripting languages
Perl, Python, Ruby, and the evolving mono
The portable C # implementation can indeed help to dilute
The traditional view of programming, but this is completely another problem.

The Linux kernel and many other free software and open source applications are written and used in C.
Compiled by GCC.

1. Compile a single source file

To perform the test, you can create the "Hello World" program:

# Include <stdio. h>
# Include <stdlib. h>

Int main (INT argc, char ** argv)
{
Printf ("Hello world! \ N ");
Exit (0 );
}

Run the following command to compile and test the Code:
# Gcc-O hello. c
#./Hello
Hello wordl!

The executable program generated by default is named A. out, but you can usually use the GCC
To specify the name of the executable program.

2. Compile multiple source files

The source file message. C contains a simple message printing function:

# Include <stdio. h>

Void goodbye_world (void)
{
Printf ("Goodbye, world! \ N ");
}

Use the "-c" mark of GCC to compile the supported library code:
# Gcc-C message. c

The output result of this process is a file named message. O, which contains compiled target code suitable for connecting to a large program.

Create a simple example program that contains a main function that calls goodbye_world.

# Include <stdlib. h>

Void goodbye_world (void ):

Int main (INT argc, char ** argv)
{
Goodbye_world ();
Exit (0 );
}

Compile this program using gcc:
# Gcc-C main. c

Now there are two target files: Message. O and Main. O. These include
The target code to be executed. To create a Linux executable program from this target code, you need to call GCC again
To execute the connection phase:
# Gcc-O goodbye message. O main. o

Run the compilation result:
#./Goodbye
Goodbye, world!

The preceding steps can also be simplified to a command, because gcc
There are built-in rules for how to compile multiple source files into one executable program.
# Gcc-O goodbye message. C main. c
#./Goodbye
Goodbye, world!

3. Use the external function library

GCC is often used in conjunction with external software libraries that contain standard routines.
Applications depend on glibc, a gnu c function library.
Example of applying an external function library:

# Include <stdio. h>
# Include <stdlib. h>
# Include <math. h>

# Define max_input 25

Int main (INT agrc, char ** argv)
{
Char input [max_input];
Double angle;

Printf ("Give me an angle (in radians) => ");
If (! Fgets (input, max_input, stdin )){
Perror ("an error occurred. \ n ");
}
Angle = strtodd (input, null );

Printf ("Sin (% E) = % E \ n", angle, sin (angle ));

Return 0;
}

Compile command:
# Gcc-O trig-LM trig. c

The "-lm" option of GCC, which tells gcc
View the mathematical Library (libm) provided by the system ). Because Linux and UNIX system function libraries are usually prefixed with "lib", we assume it exists. The real location of the function library varies with the System
Different, but it is usually located in the/lib directory or/usr/lib. There are hundreds of other required system function libraries in these directories.

4. Shared function library and static function library

The function libraries in Linux are divided into two different types: shared and static

Static function library: each time an application is compiled with a statically connected function library, the code in any referenced library function is directly included in the final binary program.

Shared function library: contains a single global version of each library function, which is shared among all applications. The mechanism behind this process is quite complex, but it relies mainly on the virtual memory capability of modern computers, it allows the physical memory containing library functions to be securely shared among multiple independent user programs.

Using the shared function library not only reduces the file capacity and Linux
The area covered by the application in the memory, and it also improves the security of the system. A shared function library that is called by many different programs at the same time may reside in the memory and be used immediately when necessary,
Instead of in the SWAp partition of the disk. This helps to further reduce some large Linux
The loading time of the application.

The preceding example of using message. C as a shared library function:

# Gcc-FPIC-C message. c
"Pic" command line flag tells gcc
The generated code should not contain references to the specific memory locations of functions and variables, because the application that uses the message code cannot know which memory address the code will connect. Compile the output file
Message. O can be used to create a shared function library. We only need to use the "-shared" mark of GCC:
# Gcc-shared-O libmessage. So message. o

Compile the above mian. C using the shared library function ligmessage. So:
# Gcc-O goodbye-lmessage-L. Message. o
"-Lmessage" indicates that GCC references the shared function library libmessage. So in the connection phase.
. "-L." indicates that the GCC function library may be in the current directory; otherwise, the GNU
The connector will find the directory of the standard system function library. In this example, the available function library cannot be found.

At this time, the compiled goodbye will prompt that the shared function library cannot be found:
#./Goodbye
./Goodbye: Error while loading shared libraries: libmessage. So: cannot
Open shared object file: no such file or directory

You can run the LDD command.
To find the function library required by a specific application. LDD searches for the path of the standard system function library and displays the version of the function library used by a specific program.

# LDD goodbye
Linux-gate.so.1 => (0x00493000)
Libmessage. So => not found
Libc. so.6 =>/lib/libc. so.6 (0 × 0097c000)
/Lib/ld-linux.so.2 (0x0095a000)

Library File libmessage. So
Cannot be found in any standard search path, and the configuration file/etc/lD. So. conf provided by the system
There is no additional entry to specify the directory containing the library file.

You need to set an environment variable LD_LIBRARY_PATH to create an additional shared function library search path,
# Export LD_LIBRARY_PATH = 'pwd'
# LDD goodbye
Linux-gate.so.1 => (0x002ce000)
Libmessage. So =>/tmp/cpro/libmessage. So (0x00b0f000)
Libc. so.6 =>/lib/libc. so.6 (0x0097c000)
/Lib/ld-linux.so.2 (0x0095a000)
Run the program
#./Goodbye
Goodbye, world!

GCC frequently uses the following options on the command line:
-C
Only preprocessing, compilation, and assembly source programs are supported without connection. The compiler generates a target file for each source program.
-O file determines that the output file is file. If the-O option is not used, the output of the default executable file is
A. Out, the output of the target file and the Assembly file is source. suffix and source. s respectively, and the output of the pre-processed C source program is stdout.
-Dmacro or-dmacro = defn act similar to # define in the source program. Example: % gcc-C
-Dhave_gdbm-dhelp_file = \ "Help \" cdict. C, where the first-
D option defines the macro have_gdbm. in the program, you can use # ifdef to check whether it is set. The second-D option defines the macro help_file as the string "help" (because
Quotation marks are actually part of the macro definition), which is useful for controlling which file the program opens.
-Umacro
Some macros are automatically defined by the compiled program. These macros can usually specify the symbols of the computer system type in which the program is compiled. You can add
-V option to view which macros are defined by GCC by default. If you want to cancel a macro definition, use the-umacro option, which is equivalent to setting the # UNDEF
Macro is placed at the beginning of the source file to be compiled.
-Idir
Add the Dir directory to the directory list of the search header file, and give priority to the default GCC search directory. If multiple-I options exist, search by the sequence of-I options on the command line. Dir can use relative paths, such as-I ../Inc.
-O
The program compilation is optimized. The Compilation Program tries to Reduce the length and execution time of the program to be compiled. However, the Compilation speed is slower than that of the program without optimization and requires a large amount of memory.
-O2 allows better optimization than-O, and the compilation speed is slow, but the execution speed of the result program is faster.
-G
Generate an extended symbol table for debugging and troubleshooting. The-G option allows the program to debug with the GNU debug program GDB. Optimization and debugging are usually incompatible. Using the-G and-O (-O2) options at the same time often produces strange running results for the program. Therefore, do not use the-G and-O (-O2) options at the same time.
-FPIC or-FPIC generates location-independent target code, which can be used to construct a shared function library.
The above is the GCC compilation option. You can also use the connection option on the GCC command line. In fact, GCC passes all unrecognized options to the Connection Program lD. The Connection Program LD splits several target files and libraries
The program is combined into an executable file, which must be referenced by external variables, external processes, library programs, and so on. However, we never need to explicitly call lD. Using the GCC command to connect to various files is very simple,
Even if the library program is not listed in the command line, GCC can ensure that some library programs appear in the correct order.
Common GCC connection options include the following:
-Ldir
Add the Dir directory to the directory list of the library file specified by the search-L option, and give priority to the default GCC search directory. If multiple-l options exist, search by the order of-l options on the command line. Dir can use relative paths. Such as-l ../lib.
-Lname
Use the libname. A function library during connection. The Connection Program searches for the library file under the directory specified by the-ldir option and under the/lib and/usr/lib directories. If the-static option is not used and libname. So function library is found, libname. So is used for dynamic connection.
-Static: do not connect to the shared function library.
-Shared should be connected to the shared function library whenever possible.
This is the default option for connecting programs on Linux. The following is an example of using gcc for connection:
% Gcc-O prog main. O subr. O-l ../lib-lany-LM

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.