学习总结:gcc/g++ 编译与连接

gcc/g++ 编译与连接

编译与连接的过程能够分解为四个步骤:预处理、编译、汇编、连接

  • 预处理:源代码文件和相关的头文件,被预处理器cpp预处理成一个后缀为 .i 的文件(选项:-E
  • 编译:把预处理完的文件进行一系列的词法分析、语法分析、语义分析以及优化后,产生相应的汇编代码文件,后缀为 .s,(选项 :-S
  • 汇编:把编译阶段生成的 .s 文件转成二进制目标代码,后缀为.o,(选项:-c
  • 连接:把每一个源代码模块独立地编译,而后按照要将它们“组装”起来。连接的主要内容就是把各个模块之间相互引用的部分都处理好,使得各个模块之间可以正常的衔接,生成最终可执行文件

例子:优化

pintA.hcode

#ifndef __PRINTA_H_
#define __PRINTA_H_

void printA();

#endif

printA.cpp开发

#include "printA.h"
#include <stdio.h>
void printA()
{
    printf("I am A.\n");
}

printB.hget

#ifndef __PRINTB_H_
#define __PRINTB_H_

void printB();

#endif

printB.cppio

#include "printB.h"
#include <stdio.h>
void printB()
{
    printf("You are B.\n");
}

语法:编译

g++ 选项 source -o target
  • source 为待处理文件,-o 后的 target 是目标文件,g++ 选项、source的文件后缀、 target的文件后缀要注意对应

预处理:class

g++ -E printA.cpp -o printA.i
g++ -E printB.cpp -o printB.i

编译:后台

g++ -S printA.i -o printA.s
g++ -S printB.i -o printB.s

汇编:gcc

g++ -c printA.s -o printA.o
g++ -c printB.s -o printB.o

连接:语法

g++ main.cpp printA.o printB.o -o main

运行

./main

输出结果:

I am A.

You are B.

参考:《后台开发核心技术与应用实践》

相关文章
相关标签/搜索