C++ hello world编译过程

main.cpp

#include <iostream>


int main(int argc, char* argv[]){
  std::cout << "hello world" << std::endl;

}

编译四步

1️⃣preprocessing, 2️⃣compilation proper, 3️⃣assembly and 4️⃣linking

使用g++ 编译

  1. 直接使用g++ main.cpp
    生成 a.out文件, 直接运行,终端显示 hello world
  2. 按步骤编译
    2.1 预处理(preprocessing)g++ -E main.cpp > main.i
    • 必须用重定向才能输出到文件。
    • -E的意思:编译器在做完预处理之后就停止,预处理后的源码直接输出到标准输出,忽略无需预处理的输入文件。
    • 打开main.i image
      发现被替换的#include <iostream>长达4万多行···

2.2 编译(compilation proper)(为汇编文件)g++ -S main.cpp
- 生成main.s 文件
- -S 的意思:编译器在做完编译之后就停止,默认将文件后缀名替换为.s,忽略无需编译的输入文件。
2.3 汇编(assembly)
- 将汇编代码生成为目标文件(机器代码)g++ -c main.cpp 或者g++ -c main.s
- 默认生成 main.o
2.4 链接(linking)
- g++ main.o -L /usr/lib/ 默认生成a.out
- 用-o 参数指定输出文件名

posted @ 2022-11-01 15:43  略略略——  阅读(147)  评论(0编辑  收藏  举报