• ubuntu编写makefile编译c++程序


    常见的编译工具

    • gcc/g++
    • visual c++
    • clang

    编译一个简单的程序
    main.cpp

    #include 
    
    int main()
    {
        std::cout << "hello world" << std::endl;
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    gcc 编译
    源文件(.cpp)编译生成目标文件(.o)

    gcc -c main.cpp -o main.o
    
    • 1

    gcc 链接
    目标文件(.o)链接生成可执行文件

    gcc main.o -o main
    
    • 1

    报错

    root@31135f61935f:~/hello# gcc main.o -o main
    /tmp/ccVubJEp.o: In function `main':
    main.cpp:(.text+0xa): undefined reference to `std::cout'
    main.cpp:(.text+0xf): undefined reference to `std::basic_ostream >& std::operator<<  >(std::basic_ostream >&, char const*)'
    main.cpp:(.text+0x14): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
    main.cpp:(.text+0x1c): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
    /tmp/ccVubJEp.o: In function `__static_initialization_and_destruction_0(int, int)':
    main.cpp:(.text+0x4a): undefined reference to `std::ios_base::Init::Init()'
    main.cpp:(.text+0x59): undefined reference to `std::ios_base::Init::~Init()'
    collect2: error: ld returned 1 exit status
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    解决方法:
    方式一

    gcc -c main.cpp -o main.o
    gcc main.o -o main -lstdc++
    
    • 1
    • 2

    两条命令合并

    gcc main.cpp -o main -lstdc++
    
    • 1

    方式二

    g++ -c main.cpp -o main.o
    g++ main.o -o main
    
    • 1
    • 2

    两条命令合并

    g++ main.cpp -o main
    
    • 1

    c++ 编译流程

    1. 预处理
    2. 编译
    3. 汇编
    4. 链接
      在这里插入图片描述
      预处理
      把 #include 语句以及一些宏插入程序文本中,得到 *.i 文件。
    g++ -E main.cpp -o main.i
    
    • 1

    编译
    将文本文件 *.i 文件编译成文本文件 *.s 的汇编语言程序。

    g++ -S main.i -o main.s
    
    • 1

    汇编
    将 *.s 翻译成机器语言的二进制指令,并打包成一种叫做可重定位目标程序的格式,并将结果保存在 *.o 文件中。

    g++ -c main.s -o main.o
    
    • 1

    链接
    合并全部 *.o 文件,得到可执行文件。

    g++ main.o -o main
    
    • 1

    预处理、编译、汇编合并

    g++ -c main.cpp -o main.o
    g++ main.o -o main
    
    • 1
    • 2

    预处理、编译、汇编、链接合并

    g++ main.cpp -o main
    
    • 1

    参考视频:

    如何编译 C++ 程序:轻松搞定 Makefile

    参考链接:
    如何编译 C++ 程序:轻松搞定 Makefile

  • 相关阅读:
    Vue教学19:Element UI组件深入探索,构建精致的Vue应用界面
    理论和实践详解RabbitMQ惰性/延迟队列(lazy queues)(带测试样例及分析)
    归并排序(java)
    工业级路由器如何异地组网及其作用
    linux 信号
    Python入门教程 | Python3 元组(tuple)
    软考:中间件
    您可知道如何通过`HTTP2`实现TCP的内网穿透???
    Docker发布简单springboot项目
    6-2 顺序表操作集分数 20
  • 原文地址:https://blog.csdn.net/qq_44091004/article/details/133722816