Source | Low Concurrency Programming
Author | Flash Player
As a Java programmer, I always forget the basic usage of gcc and am not very familiar with it. Today, this article records the basic knowledge of gcc in the simplest way.
The Compilation Process
Write a hello.c code.
#include <stdio.h>
#define STR "hello world\n"
void main() {
printf(STR);
}
Step One: Preprocessing
It actually consists of the following three actions:
gcc -E hello.c -o hello.i
Step Two: Compilation
Convert to assembly language.
gcc -S hello.i -o hello.s
Step Three: Assembly
Convert to binary (ELF relocatable).
gcc -c hello.s -o hello.o
Step Four: Linking
This is specifically divided into dynamic linking and static linking.
# Dynamic linking
gcc hello.o -o hello
# Static linking
gcc hello.o -o hello -static
Creating a Static Library
Write an addition function.
int add(int a, int b) {
return a+b;
}
Compile to .o.
gcc -c add.c -o add.o
Create a static library.
ar rcs libadd.a add.o
Write test code.
#include <stdio.h>
void main(){
printf("%d", add(1,2));
}
Compile to executable file.
# Method One
gcc test.c -o test libadd.a
# Method Two
gcc test.c -o test -static -ladd -L ./
Execute.
./test
3
Creating a Dynamic Library
Write an addition function.
int add(int a, int b) {
return a+b;
}
Compile to .o.
gcc -c add.c -o add.o -fPIC
Create a dynamic library.
gcc -shared -o libadd.so add.o
The above two steps can also be done directly from the source file in one go.
gcc -fPIC -shared -o libadd.so add.c
Write test code.
#include <stdio.h>
void main(){
printf("%d", add(1,2));
}
Compile to executable file.
gcc test.c -o test -ladd -L ./
Execution results in an error.
./test
error while loading shared libraries: libadd.so:
cannot open shared object file: No such file or directory
Because the specified dynamic library cannot be found during execution.
Let’s put libadd.so in the default dynamic library search path during execution, such as /lib64.
cp libadd.so /lib64
Executing again succeeds.
./test
3
Check the linking information of the binary file, and we can also find that our libadd.so is effective.
ldd test
linux-vdso.so.1 => (0x00007ffe0f597000)
libadd.so => /lib64/libadd.so (0x00007fa5ab29f000)
libc.so.6 => /lib64/libc.so.6 (0x00007fa5aaed1000)
/lib64/ld-linux-x86-64.so.2 (0x00007fa5ab4a1000)
Alright, that’s the process of compilation, creating static libraries, and creating dynamic libraries. First, remember these basic facts about gcc, and then go study the principles!