-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgcc_guide
More file actions
53 lines (41 loc) · 3.1 KB
/
gcc_guide
File metadata and controls
53 lines (41 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Hello everyone!
My presetation is about gcc .
The topic is how does the c source code complie into the binary file.
First the steps includes preprocessing -> compilation -> assembly -> linking
//preprocessing: gcc -E hello.c -o hello.i
//compilation: gcc -S hello.i -o hello.s
//assembly: gcc -c hello.s -o hello.o
//linking: gcc hello.o -o hello
four steps:
First we use gcc command with -E to finish preprocessing(preprocessing: gcc -E hello.c -o hello.i)
The output is in the form of preprocessed source code, which is sent to the standard output.
Second we use gcc command with -S to deal with the source code into assemble file.(compilation: gcc -S hello.i -o hello.s)
The output is in the form of an assembler code file .We can use objdump command to read the assemble file(objdump -S hello.o)
Last we link the object file into the binary file.(gcc hello.o -o hello )
If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o,
its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output.
Above all ,we conclude the procedure of compliing the source code
Finally let's talk about generating the share object with gcc .
we should use -share -fPIC and -O2 to complie the specific file
// 动态库
gcc -c hello.c
gcc -shared -fPCI -o libmyhello.so hello.o
gcc -o hello main.c -L. -lmyhello
最主要的是GCC命令行的一个选项:
-shared 该选项指定生成动态连接库(让连接器生成T类型的导出符号表,有时候也生成弱连接W类型的导出符号),不用该标志外部程序无法连接。相当于一个可执行文件
-fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的。
-L.:表示要连接的库在当前目录中
-ltest:编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名称
LD_LIBRARY_PATH:这个环境变量指示动态连接器可以装载动态库的路径。
当然如果有root权限的话,可以修改/etc/ld.so.conf文件,然后调用 /sbin/ldconfig来达到同样的目的,不过如果没有root权限,那么只能采用输出LD_LIBRARY_PATH的方法了。
gcc -O2 -fPIC -shared libbeep.c -o libbeep.so.0
-O2
Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As
compared to -O, this option increases both compilation time and the performance of the generated code.
-fPIC
If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit
on the size of the global offset table.
-shared
Produce a shared object which can then be linked with other objects to form an executable. Not all systems support this
option. For predictable results, you must also specify the same set of options that were used to generate code (-fpic,
-fPIC, or model suboptions) when you specify this option.