Getting started with GCC

Source: Internet
Author: User
Tags mathematical functions gfortran

This article is an introductory article for beginners of GCC, so the content is relatively simple. If you know that the following three commands can compile C ++, you don't have to waste time in this article.

Code:G ++-wall hellocpp. cpp
Gcc-wall hellocpp. cpp-lstdc ++
Gfortran-wall hellocpp. cpp-lstdc ++

Note: The latest version of this article is http://wiki.ubuntu.org.cn/Gcchowto in wiki (we recommend that you directly access the version in wiki)
If you want to find an integrated development environment, you can access the http://wiki.ubuntu.org.cn/C_Cpp_IDE
To build a GTK or QT compiling environment, visit http://wiki.ubuntu.org.cn/gtkand qtcompilation environment installation and configuration.


Note: Make sure that you have installed the build-essential software package before you start.

Compile a simple C program

The typical example of getting started with C language is Hello world. The following is a sample code:

Code:# Include <stdio. h>
Int
Main (void)
{
Printf ("Hello, world! /N ");
Return 0;
}

Assume that the code is saved as the file 'hello. C '. Compile the file with GCC and run the following command:

Code:$ Gcc-wall hello. C-O hello

This command compiles the code in the file 'hello. c' into a machine code and stores it in the executable file 'Hello. The name of the machine code file is specified through the-O option. This option is usually used as the last parameter in the command line. If omitted, the default output file is 'a. out '.

Note that if the file with the same name as the executable file already exists in the current directory, it will be overwritten.

Option-wall enables almost all common warnings of the compiler-it is strongly recommended that you always use this option. The compiler has many other warning options, but-wall is the most commonly used. By default, GCC does not generate any warning information. When writing C or C ++ programs, the compiler warning is very helpful for detecting program problems.

In this example, the compiler uses the-wall option without generating any warning, because the example program is completely legal.

To run the program, enter the executable file path as follows:

Code:$./Hello
Hello, world!

This loads the executable file into the memory and causes the CPU to start executing its contained commands. Path./indicates the current directory. Therefore,./Hello loads and executes the executable file 'hello' in the current directory '.

Capture Error

As mentioned above, the compiler warning is a very important helper when programming in C or C ++. To illustrate this, the following example contains a subtle error: an integer is incorrectly specified with a floating point Controller '% F '.

Code:# Include <stdio. h>

Int
Main (void)
{
Printf ("two plus two is % F/N", 4 );
Return 0;
}

The error is not obvious at a glance, but it can be captured by the compiler, as long as the warning option-wall is enabled.

Compile the above program 'bad. c' and get the following message:

Code:$ Gcc-wall bad. C-o bad
Bad. C: In function 'main ':
Bad. C: 6: Warning: Double format, different type Arg (ARG 2)

This indicates that the format string in row 'bad. c' is incorrectly used. The GCC message always has the following format file name: row number: Message. The compiler treats errors differently from warnings. The former blocks compilation, while the latter indicates possible problems but does not block compilation.

In this example, for integer values, the correct format controller should be % d.

If-wall is not enabled, the program appears to be compiled normally, but an incorrect result is returned:

Code:$ GCC bad. C-o bad
$./Bad
Two plus two is 2.585495

Obviously, it is very dangerous to do not check the warning when developing a program. If a function is improperly used, the program may crash or produce incorrect results. Enable the compiler warning option-wall to capture most common errors in C programming.

Compile multiple source files

A source program can be divided into several files. This facilitates editing and understanding, especially when the program is very large. This also makes it possible to compile each part independently.

In the following example, we split the hello World Program into three files: 'main. C', 'Hello _ fn. c' and the header file 'hello. H '. This is the main program 'main. C ':

Code:# Include "Hello. H"
Int
Main (void)
{
Hello ("world ");
Return 0;
}

In the previous example 'Hello. C ', we call the library function printf. In this example, we use a definition in the file 'Hello _ fn. the Hello function in C replaces it.

The main program contains the header file 'hello. H', which contains the hello function declaration. We do not need to include the system header file 'stdio. H' In the 'main. c' file to declare the function printf, because 'main. c' does not directly call printf.

The declaration in the file 'hello. H' specifies the prototype of the hello function with only one line.

Code:Void Hello (const char * Name );

The Hello function is defined in the 'hello _ fn. c' file:

Code:# Include <stdio. h>
# Include "Hello. H"

Void
Hello (const char * name)
{
Printf ("Hello, % s! /N ", name );
}

Statement # include "file. H "and # include <file. h> different: the former searches for the 'file. 'file in the current directory before searching for the system header file directory. H ', the latter only searches for the system header file without viewing the current directory.

Compile the source file with GCC and run the following command:

Code:$ Gcc-Wall Main. c hello_fn.c-O newhello

In this example, we use option-O to specify a different name for the executable file newhello. Note that the header file 'hello. H' is not specified in the command line. The # include "Hello. H" Directive in the source file causes the compiler to automatically include it to the appropriate location.

To run this program, enter the path name of the executable file:

Code:$./Newhello
Hello, world!

Each part of the source program is compiled into a single executable file, which produces the same result as the previous example.

Link External library

A library is a collection of pre-compiled object files that can be linked to a program. The static library is stored as a special archive file with '..

The standard system library can be found in the/usr/lib and/lib directories. For example, in Unix-like systems, the C-language mathematical library is generally stored as a file/usr/lib/libm.. The prototype Declaration of the function in this library is in the header file/usr/include/Math. h. The C standard library is stored as/usr/lib/libc. A, which contains functions specified by the ANSI/iso c standard, such as 'printf '. For every C program, libc. A is linked by default.

The following is an example of calling the sin function in library libm.:

Code:# Include <math. h>
# Include <stdio. h>

Int
Main (void)
{
Double X = sin (0, 2.0 );
Printf ("the value of sin (2.0) is % F/N", X );
Return 0;
}

An attempt to generate an executable file from this file will result in a link phase error:

Code:$ Gcc-wall Calc. C-o calc
/Tmp/FIG: In function 'main ':
Calc. c :(. Text + 0x1b): Undefined reference to 'sin'

Function sin, which is not defined in this program and is not in the default library 'libc. A'. Unless specified, the compiler will not link 'libm. '.

To enable the compiler to link sin to the main program 'calc. C', we need to provide the Math Library 'libm. '. One easy-to-think but troublesome way is to explicitly specify it in the command line:

Code:$ Gcc-wall Calc. c/usr/lib/libm. A-O calc

The function library 'libm. A' contains the target files of all mathematical functions, such as sin, cos, exp, log, and SQRT. The linker searches all files to find the target file containing the sin.

Once the target file containing sin is found, the main program can be linked and a complete executable file can be generated:

Code:$./Calc
Value of sin (2.0) is 0.909297

The executable file contains the machine code of the main city and the machine code of sin in the 'libm. A' function library.

To avoid specifying a long path in the command line, the compiler provides a quick option '-l' for the linked function library '. For example, the following command

Code:$ Gcc-wall Calc. C-lm-O calc

It is equivalent to the command '/ usr/lib/libm. A' for the specified full path of the library above.

In general, option-lname enables the linker to try to link the library file libname. a In the system library directory. A large program usually uses many-l options to specify the Math Library, graphics library, and network library to be linked.

Compile C ++/FORTRAN

You may know that GCC is the acronym of the GNU Compiler Collection. It can compile C, C ++, objective-C, Fortran, Java, and Ada languages.

Previously we only talked about C language. How can we compile other languages with GCC?

Compile C ++

(The following two commands are equivalent, but I believe you will choose the former ^_^)

Code:G ++-wall hello. cpp-O hello
Gcc-wall hello. cpp-O hello-lstdc ++

Compile FORTRAN

If your GCC version is greater than or equal to 4.0, choose one of the following commands.

Code:Gfortran-wall hello. F-O hello
Gcc-wall hello. F-O hello-lgfortran-lgfortranbegin

If the GCC version is <4.0, choose one of the following commands:

Code:G77-wall hello. F-O hello
Gcc-wall hello. F-O hello-lfrtbegin-lg2c this article is transferred from the Ubuntu Chinese Forum

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.