As a Java programmer , yes gcc I can't remember the basic use of , Very unskilled , Write an article today and record it in the simplest way .

Compilation process

Write a hello.c code
#include <stdio.h> #define STR "hello world\n" void main() {     printf(STR); }

First step : Pretreatment (preprocess)

It's actually the following three actions

1. Header file expansion

2. Macro definition direct replacement

3. If conditional compilation does not hold, remove it
gcc -E hello.c -o hello.i

Step two : compile (compile)

Convert to assembly language
gcc -S hello.i -o hello.s

Step 3 : assembly (assemble)

Convert to binary (ELF relocatable)
gcc -c hello.s -o hello.o

Step 4 : link (link)

It is divided into dynamic link and static link
#  dynamic link gcc hello.o -o hello #  Static link gcc hello.o -o hello -static

Static library production

Write an addition function .
int add(int a, int b) {     return a+b; }
Compile into .o
gcc -c add.c -o add.o
Make it into a static library
ar rcs libadd.a add.o
Write test code
#include <stdio.h> void main(){     printf("%d", add(1,2)); }
Compile into executable
# Writing method I gcc test.c -o test libadd.a # Writing method 2 gcc test.c -o test -static -ladd -L ./
./test 3

Dynamic library making

Write an addition function .
int add(int a, int b) {     return a+b; }
Compile into .o
gcc -c add.c -o add.o -fPIC
Make it into a dynamic library
gcc -shared -o add.o
The above two steps can also be done directly from the source file in one step
gcc -fPIC -shared -o add.c
Write test code
#include <stdio.h> void main(){     printf("%d", add(1,2)); }
Compile into executable
gcc test.c -o test -ladd -L ./
Error reporting during execution
./test error while loading shared libraries: 
cannot open shared object file: No such file or directory
Because the specified dynamic library cannot be found during execution .

Then let's take  Put it under the default search path of dynamic library during execution , such as  /lib64
cp /lib64
Execute it again and it will succeed
./test 3
View binary link information , You can also find our It's working .
ldd test =>  (0x00007ffe0f597000) => /lib64/ (0x00007fa5ab29f000) => /lib64/ (0x00007fa5aaed1000)
   /lib64/ (0x00007fa5ab4a1000)

okay , The above is compilation , Static library production , The process of making dynamic library , Remember this first gcc Basic knowledge of , Want more knowledge , plus QQ group :873250202 receive !

©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage Python Study notes ( one )evo Tool usage problems ——Degenerate covariance rank, Umeyama alignment is not possibleRISC-V_GD32VF103-TIMER0 timer interrupt java Array subscript variable _Java Basic grammar : array be based on stm32 Control four-wheel trolley motor drive ( one ) be based on redis Design of liking function Software engineering career planning mysql Query random data by conditions _MySQL Random query of several qualified records centos7 install RabbitMq