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

gcc/g++ 编译与链接

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

例子:

pintA.h

#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.h

#ifndef __PRINTB_H_
#define __PRINTB_H_

void printB();

#endif

printB.cpp

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

语法:

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

预处理:

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

汇编:

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.

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

转载于:https://www.cnblogs.com/pz-Feng/p/8284121.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值