TrumanWong

gcc

C/C++ based compiler

Supplementary instructions

gcc command uses the C/C++-based compiler launched by GNU. It is the most widely used compiler in the open source field. It has powerful functions and the compiled code supports performance optimization. Many programmers now use GCC. How can we use GCC better. Currently, GCC can be used to compile programs in C/C++, FORTRAN, JAVA, OBJC, ADA and other languages. You can choose to install supported languages according to your needs.

grammar

gcc(options)(parameters)

Options

-o: Specify the generated output file;
-E: Only perform compilation preprocessing;
-S: Convert C code to assembly code;
-wall: display warning information;
-c: Only compile operations are performed, no linking operations are performed.
-l: used to specify the library to be linked to by the program. The -l parameter is followed by the library name.
-I: Directory to search for header files

Parameters

C source file: Specify the C language source code file.

Example

Common compilation command options

Assume that the source program file is named test.c

Compile and link without options

gcc test.c

Preprocess, assemble, compile and link test.c into an executable file. No output file is specified here, the default output is a.out.

option -o

gcc test.c -o test

Preprocess, assemble, compile and link test.c to form the executable file test. The -o option is used to specify the file name of the output file.

Option -E

gcc -E test.c -o test.i

Preprocess test.c to output the test.i file.

OPTION -S

gcc -S test.i

Assemble the preprocessing output file test.i into a test.s file.

option -c

gcc -c test.s

Compile the assembly output file test.s and output the test.o file.

No option link

gcc test.o -o test

Link the compilation output file test.o into the final executable file test.

Option -O

gcc -O1 test.c -o test

Compile the program using compilation optimization level 1. The level is 1~3. The larger the level, the better the optimization effect, but the longer the compilation time.

Compilation method of multi-source files

If you have multiple source files, there are basically two ways to compile:

Suppose there are two source files test.c and testfun.c

Compile multiple files together

gcc testfun.c test.c -o test

Compile testfun.c and test.c respectively and link them into the test executable file.

**Compile each source file separately, and then link the compiled output target file. **

gcc -c testfun.c #Compile testfun.c into testfun.o
gcc -c test.c #Compile test.c into test.o
gcc testfun.o test.o -o test #Link testfun.o and test.o into test

Comparing the above two methods, the first method requires all files to be recompiled when compiling, while the second method can only recompile modified files, and unmodified files do not need to be recompiled.

Load dynamic link library

gcc hello.c -lpthread -o hello

Manually add file header path

gcc hello.c -lpthread -I /lib64/ -o hello