zoukankan      html  css  js  c++  java
  • g++编译流程

    测试程序test.cpp如下所示:

    #include <iostream>
    using namespace std;
    #define MAX 9
    int main()
    {
        //just for test
        cout << MAX << endl;
        cout << "Hello world!" << endl;
    }
    

    g++编译主要分为四个阶段进行,即预处理(Preprocessing)、编译(Compilation)、汇编(Assembly)和连接(Linking)。

    1.预处理

    g++ -E test.cpp -o test.i
    

    g++的-E选项,可以让编译器在预处理后停止,并输出预处理结果;输出的test.i文件中存放着test.cpp经预处理之后的代码;也可以通过g++ -E test.cpp直接在命令行窗口中输出预处理后的代码;

    如下图所示,在本例中,预处理结果就是将iostream文件(路径为/usr/include/c++/4.8)中的内容插入到test.cpp中,还会做宏的替换、注释的消除;

    iostream与test.i的对比:

    test.i文件最后的部分:

    # 2 "test.cpp" 2
    using namespace std;
    
    int main()
    {
        //消除注释
        cout << 9 << endl;//宏替换
        cout << "Hello world!" << endl;
    }
    

    2.编译

    预处理之后,可以直接对生成的test.i文件进行编译,生成汇编代码:

    g++ -S test.i -o test.s
    

    g++的-S选项,表示在程序编译期间,在生成汇编代码后停止,-o输出汇编代码文件;

    3.汇编

    对于编译生成的汇编代码文件test.s,gas汇编器负责将其编译为目标文件,

    g++ -c test.s -o test.o
    

    4.连接

    g++链接器是gas提供,负责将程序的目标文件与所依赖的所有附加目标文件连接起来,最终生成可执行文件,附加目标文件依赖静态连接库(.a或者.lib)和动态连接库(.so或.dll)。

    对于汇编生成的test.o,将其与C++标准输入输出库进行连接,最终生成可执行程序test。

    g++ test.o -o test
    

    在命令行窗口中,执行./test,即可输出:

    9
    Hello world!
    

    5.多个文件的编译

    6.库文件连接

    7.g++与gcc的联系和区别

  • 相关阅读:
    django 如何重用app
    vim常用命令
    linux find grep
    linux su su-的区别
    linux定时任务crontab
    linux shell的单行多行注释
    python字符串的截取,查找
    gdb调试
    python字符转化
    python读写文件
  • 原文地址:https://www.cnblogs.com/zhbzz2007/p/5474175.html
Copyright © 2011-2022 走看看