An Introduction to GCC Notes

Chapter 1: Introduction

Chapter 2: Compiling a C program

The -o option is usually given as the last argument on the command line.

If the -o option is omitted, the output is written to a default file called ‘a.out’.

Always using -Wall option.

The messages produced by GCC always have this form:

1
file:line-number:message

The linker fills in these missing addresses when it produces the executable.

2.4.1 Creating object file from source files

The command-line option -c is used to compile a source file to an object file.

2.4.2 Creating executables from object files

Use gcc to link the object files together and fill in the missing addresse of external functions.

A separate program, linker ld.

The object file which contains the definition of a function should appear after any files which call that function.

2.5 Recompiling and relinking

Linking is faster than compilation.

2.6 Linking with external libraries

A library is a collection of precompiled object files which can be linked into programs.

Libraries are typically stored in special archive files with the extension .a, refferred to as static libraries.

They are created from object files with a saparate tool, the GNU archiver ar, and used by the linker to resolve references to functions at compile-time.

The standard system libraries are usually found in the directories /usr/lib and /lib.

1
$ gcc -Wall calc.c /usr/lib/libm.a -o calc

The library libm.a contains object files for all the mathematical functions.

使用缩写, the compiler option -lNAME will attempt to link object files with a library file libNAME.a in the standard library directories.

1
$ gcc -Wall calc.c -lm -o calc

Searching from left to right. 左边缺少的到右边找。

2.7 Using library header files

In order to declare function arguments and return values with the correct types. 没有声明,参数的类型会出错。

Chapter 3: Compilation options

By default, gcc searches the following directories for header files:

1
2
/usr/local/include
/usr/include

For libraries:

1
2
/usr/local/lib
/usr/lib

Local 的优先级更高。

You should never place the absolute paths of header files in #include statement.

-I option or INCLUDE_PATH variable. 可指定额外的#include 路径。

-L option or LIBRARY_PATH variable. 可指定额外的 link path.

1
$ gcc -Wall -I/opt/gdbm-1.8.3/include -L/opt/gdbm-1.8.3/lib demain.c -lgdbm

若设置了C_INCLUDE_PATHCPLUS_INCLUDE_PATHLIBRARY_PATH 就不用使用-I-L选项。

3.1.3 Extended search paths

1
DIR1:DIR2:DIR3:...

or

1
$ gcc -I. -I/opt/include

多次使用-I or -L.

查找顺序:

1. command-line option `-I` and `-L`, from left to right
2. directories specified by environment variables, such as C_INLUDE_PATH and LIBRARY_PATH
3. default system directories

3.2 Shared libraries and static libraries

External libraries are usually provided in two forms:

1. static libraries, '.a' file
2. shared libries, '.so' file

Dynamic linking makes executable files smaller and saves disk space.

shared libraries 比 static library 更好。

Shared object file is used in preference to the static library.

static library 包含所有的function的machine code, 而 shared object file 只包含一部分。

By default, the loader searches for shared libraries only in a predefined set of system deirectories.

Setting load path: use variable LD_LIBRARY_PATH

Adding new:

1
$ LD_LIBRARY_PATH=/opt/gdbm-1.8.3/lib:$LD_LIBRARY_PATH

Option -static to avoid using shared library.

3.3 C language standards

Controling the dialect of C, use -ansi and -pedantic.

针对与C版本之间的差异。

3.3.1 ANSI/ISO

A valid ANSI/ISO program may be incompatible with the extention in GNU C.

_GNU_SOURCE, which enable extensions in the GNU C library.

1
$ gcc -Wall -ansi -D_GNU_SOURCE pi.c

3.3.3 Selecting special standards

The special language standard used by GCC can be controled with the ‘-std’ option.

1
-std=c99

3.4 Warning options in -Wall

Warning options can also be selected individually. 如:

1
2
3
4
5
-Wcomment

-Wformat

...

3.5 Additional warning options

-W a general option similar to -Wall.

4 Using the preprocessor

The GNU C preprocessor cpp.

It expands macros in source files before they are compiled.

4.1 Defining macro

The gcc option -DNAME defines a preprocessor macro NAME from the command line.

1
$ gcc -Wall -DTEST dtest.c

gcc 自动定义的 macro, with a double-underscore prefix __:

查看:

1
$ cpp -dM /dev/null

4.2 Macro with values

-DNAME=VALUE:

1
$ gcc -Wall -DNUM=100 dtestval.c

It is a good idea to surround macros by parenthesses.

When a macro is defined with -D alone, gcc used a default value of 1.

Empty value:

1
-DNAME=""

Define a macro message:

1
-DNAME="\"Hello, World!\""

4.3 Preprocessing source files

To see the effect of the preprocessor on source file directly, using the -E option.

-save-temps option, the preprocessed output will be available in the file hello.i.

5 Compiling for debugging

-g option to store additional debugging information in object files and executables.

GNU Debugger gdb.

Storing the names of functions and variables, with their corresponding source code line-numbers.

5.1 Examining core files

The core file can be used to find the line where the program stopped, and the values of its variables at that point.

A null pointer will only cause a problem at run-time, so the option -Wall does not produce any warning.

Whenever the error message core dumped is displayed, the operating system should produce a file called core in the current directory.

The term segmentation fault refers to the fact that the program tried to access a restricted memory segment outside the area of memory which had been allocated to it.

In the GNU Bash shell the command ulimit -c control the maximum size of core files.

Any size to be written:

1
$ ulimit -c unlimited

only apply to the current shell.

Loading the core file into the GNU Debugger gdb:

1
$ gdb EXEECUTABLE-FILE CORE-FILE

both the original executable file and the core file are required for debugging.

6 Compiling with optimization

6.1 Source-level optimization

Two type:

- common subexpression elimination
- function inlining

6.1.1 Common subexpression elimination

Reusing already-computed results.
如:

1
x = cos(v)*(1+sin(u/2)) + sin(w)*(1-sin(u/2))

重写为:

1
2
t = sin(u/2);
x = cos(v)*(1+t) + sin(w)*(1-t);

可以 increase the speed and reduces the size of the code.

6.1.2 Function inlining

Increase the efficiency of frequently-called functions.

Replacing calls to a function by the code of the function itself.

Eliminating the function call.

The function being suitably small.

6.2 Speed-space tradeoffs

Choose between speed and memory is referred to as speed-space tradeoffs.

6.2.1 Loop unrolling

将循环拆开,这样可以减少测试的时间:

1
2
3
for(i = 0; i < 8; i++) {
y[i] = i;
}

改为:

1
2
3
4
5
6
7
8
y[0] = 0;
y[1] = 1;
y[2] = 2;
y[3] = 3;
y[4] = 4;
y[5] = 5;
y[6] = 6;
y[7] = 7;

6.3 Scheduling

The results become available to later instructions at the right time.

6.4 Optimization levels

Numbered from 0-3.

The command line option -OLEVEL.

1
2
3
4
5
6
7
8
9
10
11
'-O0' or no '-O', default: perform no optimization.

'-O1' or '-O', do not require any speed-space tradeoffs, smaller and faster than with '-O0'

'-O2', it provide maximum optimization without increasing the executable size.

'-O3', may increase the speed but increase the size.

'-funroll-loops', turns on loop-unrolling.

'-Os', produce the smallest possible executable.

The cost of optimization includes greater complexity in debugging, and increased time and memory requirements during compilation.

6.5 Examples

The run-time of the program can be measured using the time command in the GNU Bash shell.

1
$ time ./a.out

Optimizations may not necessarity make a program faster in every case.

6.6 Optimization and debugging

6.7 Optimization and compiler warning

-Wall 应该看成,-Wall.

7 Compiling a C++ program

It compiles C++ source code directly into assembly language.

7.1 Compiling a simple C++ program

Using g++ instead of gcc.
p56

9 Troubleshooting

To display a complete list of options for gcc and its associated program:

1
$ gcc -v --help

10 Compiler-related tools

GNU archiver ar, for creating libaries, and the GNU profiling and coverage testing programs, gprof and gcov.

10.1 Creating a library with the GNU archiver

Combining a collection of object files into a single archive file.

1
$ ar cr libhello.a hello_fn.o bye_fn.o

The option cr stands for “create and replace”. ar does not require a prefix ‘-‘ for its options.

The first argument ‘libhello.a’ is the name of the library, The remaining arguments are the name of the object files to be copied into the library.

option t, list the object file in an existing library:

1
2
3
$ ar t libhello.a
hello_fn.o
bye_fn.o

10.2 Using the profiler gprof

Measuring the performance of a program.

To use profiling, the program must be compiled and linked with the -pg profiling option:

1
2
$ gcc -Wall -c -pg collatz.c
$ gcc -Wall -pg collatz.o

If the program consists of more than one source file then the ‘-pg’ option should be used when compiling each source file, and used again when linking the object files to create the final executable.

The executable must be run to create the profiling data:

1
$ ./a.out

10.3 Converage testing with gcov

It analyses the number of times each line of a program is executed during a run.

To find areas of the code which are not used, or which are not exercised in testing.

11 How the compiler works

The GNU Compiler, gcc or g++.

The GNU Assembler, as.

The GNU Linker, ld.

11.1 An overview of the compilation process

The following stages:

- preprocessing (to expand macros)
- compilation (from source code to assembly language)
- assembly (from assembly language to machine code)
- linking (to create the final executable)

Can be seen using the ‘-v’ option described earlier.

11.2 The preprocessor

1
$ cpp hello.c > hello.i

11.3 The compiler

1
$ gcc -Wall -S hello.i

11.4 The assembler

Convert assembly language into machine code and generate an object file.

When there are calls to external functions in the assembly source file, the assembler leaves the addresses of the external functions undefined.

1
$ as hello.s -o hello.o

11.5 The linker

The linking of object files to create an executable.

The entire linking process is handled transparently by gcc when invoked as follows:

1
$ gcc hello.o

12 Examining compiled files

12.1 Identifying files

1
$ file a.out

12.2 Examining the symble table

1
$ nm a.out

12.3 Finding dynamically linked libraries

1
$ ldd a.out

An Introduction to GCC Notes
http://example.com/2022/07/23/An-Introduction-to-GCC-Notes/
作者
Jie
发布于
2022年7月23日
许可协议