ubuntu编写makefile编译c++程序

常见的编译工具

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

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

#include <iostream>

int main()
{
    std::cout << "hello world" << std::endl;
    return 0;
}

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

gcc -c main.cpp -o main.o

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

gcc main.o -o main

报错

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<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, 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

解决方法:
方式一

gcc -c main.cpp -o main.o
gcc main.o -o main -lstdc++

两条命令合并

gcc main.cpp -o main -lstdc++

方式二

g++ -c main.cpp -o main.o
g++ main.o -o main

两条命令合并

g++ main.cpp -o main

c++ 编译流程

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

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

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

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

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

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

g++ main.o -o main

预处理、编译、汇编合并

g++ -c main.cpp -o main.o
g++ main.o -o main

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

g++ main.cpp -o main

参考视频:

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

资料加载中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值