Understand the story behind gcc

1, gcc generation uses a static library and so dynamic library

1) Create a new folder test1

mkdir test1

Enter folder test1

cd test1

Use vim command to generate hello h,hello.c,main.c three documents

vim hello.h

#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);

vim hello.c

void hello(const char *name)
        printf("Hello %s!\n",name):

vim main.c

int main()
        return 0;

2) Put hello C compiled with gcc o documents

gcc -c  hello.c

3) By o file generation static library

ar -crv libmyhello.a hello.o

4) Using static libraries in programs

gcc -o hello main.c -L. -lmyhello

Run program


Try to delete the static library function before running the program

rm libmyhello.a

It is found that the program can still run, indicating that the public function hello in the static library has been connected to the target file hello.

5) By o file generation dynamic library

gcc -shared -fPIC -o libmyhello.so hello.o

6) Using dynamic libraries in programs


As a result, the program made an error

It turned out that when the program was running, it would look for the required dynamic library files in directories such as / usr/lib and / lib. If found, load the dynamic library; If it cannot be found, it will prompt an error similar to the above and terminate the program.

Transfer the file libmyhello Copy so to the directory / user/lib and run it again.

sudo mv libmyhello.so /usr/lib

The successful operation further shows that the dynamic library is needed when the program is running.

2, Static library and dynamic library of c language program

1. Custom c language program

Create sub1.0 in the test folder c,sub2.c,main1.c three documents
sub1.c: Include function x2x (divide two numbers)

float x2x(int a,int b)
        return a/b;

sub2.c: Include function x2y (multiply two numbers)

float x2y(int a,int b)
        return a*b;

main1.c: Contains the main function

int main()
        int a=4,b=2;
        printf("a= %d  b= %d\n",a,b);
        printf("x2x:a/b= %f\n",x2x(a,b));
        printf("x2y:a*b= %f\n",x2y(a,b));
        return 0;

2. Generate static library and executable program files

Compile sub1.0 using gcc C and sub2 C get o documents

gcc -c sub1.c sub2.c

Generate static library using ar command

ar -crv libsub1.a sub1.o
ar -crv libsub2.a sub2.o

Using static libraries in programs

gcc main1.c libsub1.a libsub2.a -o main2

Run program main2

3. Generate dynamic library and executable program files

Using gcc command to generate dynamic library

gcc -shared -fPIC -o libsub1.so sub1.o
gcc -shared -fPIC -o libsub2.so sub2.o

Using dynamic libraries in programs

gcc main1.c libsub1.so libsub2.so -o main3

Take two Move the so file to the directory / usr/lib

sudo mv libsub1.so /usr/lib
sudo mv libsub2.so /usr/lib

Run program

3, Compiling process of Linux gcc

In the test3 directory, create a simple C language program file test c

int main()
        printf("Hello World!\n");
        return 0;

In fact, the one-step compilation instruction of this program is GCC test c -o test
In essence, the compilation process is divided into four stages: preprocessing / precompiling → compilation → assembly → connection

1) Preprocessing / precompiling
Put the source file hello C file preprocessing to generate hello i

gcc -E test.c -o test.i

2) Compile
Will preprocess the generated hello I file compilation generates assembler hello s

gcc -S test.i -o test.s

3) Compilation
Will compile the generated hello S file assembly to generate the target file hello o

// Assembly with gcc
gcc -c hello.s -o hello.o

//Assemble with as
as -c hello.s -o hello.o

4) Connect
It is divided into static link and dynamic link to generate executable files

//dynamic link
gcc hello.c -o hello

//Static link
gcc -static hello.c -o hello

5) Program running

4, gcc compilation Toolset

1. Understand ELF documents

1) Analyze ELF files

ELF file includes the following paragraphs

  • . test: the instruction code segment of the compiled program.
  • . rodata: ro stands for read only, i.e. system data (such as Changshu const).
  • . data: initialized c program global variables and static local variables
  • . bss: uninitialized c program global variables and static local variables
  • . dbug: debug symbol table. The debugger uses this section of information to help debug

You can use the readelf -S command to view the information of each section

readelf -S test

2) Disassembly ELF

Since elf files cannot be opened as ordinary text files, if you want to directly view the commands and data contained in an ELF file, you need to use the disassembly method.

Disassemble it with objdump -D command

objdump -D test

2.as assembler

1) The first step is to download and install the nasm compiler
Download link: https://www.nasm.us/pub/nasm/releasebuilds/2.14rc16/nasm-2.14rc16.tar.gz
Copy the link to the Firefox browser in ubuntu for downloading, and check the file address after downloading

Then observe the path and find that the compressed package is in / TMP / Mozilla_ Within huo0

In the control version, execute the following commands successively to enter the folder

cd /
cd tmp
cd mozilla_huo0

Find the downloaded installation package and unzip it

tar zxvf nasm-2.14rc16.tar.gz

After decompression, execute the following commands successively for installation

cd nasm-2.14rc16/
sudo make install

Check whether the installation is successful

nasm -version

2) Compile the assembly file hello asm
New file hello ASM, the code is as follows:

; hello.asm 
section .data            ; Data segment declaration
        msg db "Hello, world!", 0xA     ; String to output
        len equ $ - msg                 ; string length 
section .text            ; Code snippet declaration
global _start            ; Specify entry function
_start:                  ; Displays a string on the screen
        mov edx, len     ; Parameter 3: string length
        mov ecx, msg     ; Parameter 2: string to display
        mov ebx, 1       ; Parameter 1: file descriptor(stdout) 
        mov eax, 4       ; System call number(sys_write) 
        int 0x80         ; Call kernel functions
                         ; Exit program
        mov ebx, 0       ; Parameter 1: exit code
        mov eax, 1       ; System call number(sys_exit) 
        int 0x80         ; Call kernel functions


nasm -f elf64 hello.asm


ld -s -o hello hello.o

Run program

3) Compare the executable program file generated by assembly and C code compilation
C language:


It is found that the program file directly generated by assembly is smaller.

5, Running c language games under linux environment

1) Download the curses library before implementing the small game

curses library is a set of function library under UNIX, which is specially used to deal with cursor movement and screen display under the terminal interface.

sudo apt-get install libncurses5 libncurses5-dev 

2) Create a small game program file and compile it

Link: Implementation of Snake game by C language compilation in Linux Environment

gcc mysnake1.0.c -lcurses -o mysnake

3) Running games

6, Experimental summary

This experiment deepened the understanding of gcc compiler, learned to generate and use static libraries and dynamic libraries with GCC commands, and both generated executable program files. In addition, we also know the purpose of software in the compilation tool set, such as ELF file format and assembly language format. Finally, I also experienced the c language games in linux environment, and had a preliminary understanding of the curses library.

7, Reference

Implementation of Snake game by C language compilation in Linux Environment
The story behind GCC compiler

Tags: Linux Ubuntu

Posted by duelist on Wed, 11 May 2022 05:27:18 +0300