当前位置: 首页 > news >正文

Linux下编译工具:gcc/g++ の最全使用教程

目录:​​​​​​​

神马是gcc/g++

简介:

gcc/g++的特点

gcc/g++编译程序的过程

gcc/g++の使用

安装gcc/g++

在CentOS下安装gcc/g++

在Ubuntu下安装gcc/g++

gcc命令选项

全部选项:

常用选项:

g++命令选项

全部选项

常用选项

gcc/g++实战

直接生成可执行文件并运行

1:生成可执行文件

(2)运行可执行文件

分过程生成可执行文件并运行

(1)预处理

(2)编译

 (3)汇编

(4)链接

(5)运行可执行文件


本文阅读用时较长,建议慢慢食用。

神马是gcc/g++

简介:

        gcc的全称是GNU Compiler Collection,它是一个能够编译多种语言的编译器。最开始gcc是作为C语言的编译器(GNU C Compiler),现在除了c语言,还支持C++、java、Pascal等语言。gcc支持多种硬件平台。而g++是GNU的c++编译器。

gcc/g++的特点

  • 是一个可移植的编译器,支持多种硬件平台。例如ARM、X86等等。
  • 不仅是个本地编译器,它还能跨平台交叉编译。所谓的本地编译器,是指编译出来的程序只能够在本地环境进行运行。而gcc编译出来的程序能够在其他平台进行运行。例如嵌入式程序可在x86上编译,然后在arm上运行。
  • 有多种语言前端,用于解析不同的语言。
  • 是按模块化设计的,可以加入新语言和新CPU架构的支持。
  • 是自由软件。任何人都可以使用或更改这个软件。

gcc/g++编译程序的过程

gcc编译程序主要经过四个过程:

  • 预处理(Pre-Processing)
  • 编译 (Compiling)
  • 汇编 (Assembling)
  • 链接 (Linking)

 如图所示:

        预处理实际上是将头文件、宏进行展开。编译阶段,gcc调用不同语言的编译器,例如c语言调用编译器ccl。gcc实际上是个工具链,在编译程序的过程中调用不同的工具。汇编阶gcc/g++调用汇编器进行汇编。链接过程会将程序所需要的目标文件进行链接成可执行文件。汇编器生成的是可重定位的目标文件,学过操作系统,我们知道,在源程序中地址是从0开始的,这是一个相对地址,而程序真正在内存中运行时的地址肯定不是从0开始的,而且在编写源代码的时候也不能知道程序的绝对地址,所以重定位能够将源代码的代码、变量等定位为内存具体地址。下面以一张图来表示这个过程,注意过程中文件的后缀变化,编译选项和这些后缀有关。


gcc/g++の使用

安装gcc/g++

在对gcc/g++有一定了解后我们就要安装他们了!

在CentOS下安装gcc/g++

打开终端,输入以下命令行:

yum install gcc
yum install gcc-c++ libstdc++-devel
yum install glibc-static

安装完成后输入: which g++,就看到g++已经安装完成(一般是在 /usr/bin 目录下)

注意:在linux下,C++的编译器不是g++这个名称,而是gcc-c++。

在Ubuntu下安装gcc/g++

安装g++编译器的命令: 

sudo apt-get install build-essential

执行完后,就完成了gcc,g++,make的安装。build-essential是一整套工具,gcc,libc等等。

输入g++ -v 查看是否成功安装。

gcc命令选项

全部选项:

打开终端输入:gcc --help

root@DESKTOP-S8VRDOE:~# gcc --help
Usage: gcc [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase.
  --help                   Display this information.
  --target-help            Display target specific command line options.
  --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...].
                           Display specific types of command line options.
  (Use '-v --help' to display command line options of sub-processes).
  --version                Display compiler version information.
  -dumpspecs               Display all of the built in spec strings.
  -dumpversion             Display the version of the compiler.
  -dumpmachine             Display the compiler's target processor.
  -print-search-dirs       Display the directories in the compiler's search path.
  -print-libgcc-file-name  Display the name of the compiler's companion library.
  -print-file-name=<lib>   Display the full path to library <lib>.
  -print-prog-name=<prog>  Display the full path to compiler component <prog>.
  -print-multiarch         Display the target's normalized GNU triplet, used as
                           a component in the library path.
  -print-multi-directory   Display the root directory for versions of libgcc.
  -print-multi-lib         Display the mapping between command line options and
                           multiple library search directories.
  -print-multi-os-directory Display the relative path to OS libraries.
  -print-sysroot           Display the target libraries directory.
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers.
  -Wa,<options>            Pass comma-separated <options> on to the assembler.
  -Wp,<options>            Pass comma-separated <options> on to the preprocessor.
  -Wl,<options>            Pass comma-separated <options> on to the linker.
  -Xassembler <arg>        Pass <arg> on to the assembler.
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor.
  -Xlinker <arg>           Pass <arg> on to the linker.
  -save-temps              Do not delete intermediate files.
  -save-temps=<arg>        Do not delete intermediate files.
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components.
  -pipe                    Use pipes rather than intermediate files.
  -time                    Time the execution of each subprocess.
  -specs=<file>            Override built-in specs with the contents of <file>.
  -std=<standard>          Assume that the input sources are for <standard>.
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries.
  -B <directory>           Add <directory> to the compiler's search paths.
  -v                       Display the programs invoked by the compiler.
  -###                     Like -v but options quoted and commands not executed.
  -E                       Preprocess only; do not compile, assemble or link.
  -S                       Compile only; do not assemble or link.
  -c                       Compile and assemble, but do not link.
  -o <file>                Place the output into <file>.
  -pie                     Create a dynamically linked position independent
                           executable.
  -shared                  Create a shared library.
  -x <language>            Specify the language of the following input files.
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension.

Options starting with -g, -f, -m, -O, -W, or --param are automatically
 passed on to the various sub-processes invoked by gcc.  In order to pass
 other options on to these processes the -W<letter> options must be used.

For bug reporting instructions, please see:
<file:///usr/share/doc/gcc-11/README.Bugs>.

这个比较复杂,如果英语特别好,且比较闲的人可以看看

常用选项:

选项名作用
-o产生目标(.i、.s、.o、可执行文件等)
-E只运行C预编译器
-S告诉编译器产生汇编程序文件后停止编译,产生的汇编语言文件拓展名为.s
-c通知gcc取消连接步骤,即编译源码,并在最后生成目标文件
-Wall使gcc对源文件的代码有问题的地方发出警告
-Idir将dir目录加入搜索头文件的目录路径
-Ldir将dir目录加入搜索库的目录路径
-llib连接lib库
-g在目标文件中嵌入调试信息,以便gdb之类的调试程序调试

g++命令选项

全部选项

root@DESKTOP-S8VRDOE:~# g++ --help
Usage: g++ [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase.
  --help                   Display this information.
  --target-help            Display target specific command line options.
  --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...].
                           Display specific types of command line options.
  (Use '-v --help' to display command line options of sub-processes).
  --version                Display compiler version information.
  -dumpspecs               Display all of the built in spec strings.
  -dumpversion             Display the version of the compiler.
  -dumpmachine             Display the compiler's target processor.
  -print-search-dirs       Display the directories in the compiler's search path.
  -print-libgcc-file-name  Display the name of the compiler's companion library.
  -print-file-name=<lib>   Display the full path to library <lib>.
  -print-prog-name=<prog>  Display the full path to compiler component <prog>.
  -print-multiarch         Display the target's normalized GNU triplet, used as
                           a component in the library path.
  -print-multi-directory   Display the root directory for versions of libgcc.
  -print-multi-lib         Display the mapping between command line options and
                           multiple library search directories.
  -print-multi-os-directory Display the relative path to OS libraries.
  -print-sysroot           Display the target libraries directory.
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers.
  -Wa,<options>            Pass comma-separated <options> on to the assembler.
  -Wp,<options>            Pass comma-separated <options> on to the preprocessor.
  -Wl,<options>            Pass comma-separated <options> on to the linker.
  -Xassembler <arg>        Pass <arg> on to the assembler.
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor.
  -Xlinker <arg>           Pass <arg> on to the linker.
  -save-temps              Do not delete intermediate files.
  -save-temps=<arg>        Do not delete intermediate files.
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components.
  -pipe                    Use pipes rather than intermediate files.
  -time                    Time the execution of each subprocess.
  -specs=<file>            Override built-in specs with the contents of <file>.
  -std=<standard>          Assume that the input sources are for <standard>.
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries.
  -B <directory>           Add <directory> to the compiler's search paths.
  -v                       Display the programs invoked by the compiler.
  -###                     Like -v but options quoted and commands not executed.
  -E                       Preprocess only; do not compile, assemble or link.
  -S                       Compile only; do not assemble or link.
  -c                       Compile and assemble, but do not link.
  -o <file>                Place the output into <file>.
  -pie                     Create a dynamically linked position independent
                           executable.
  -shared                  Create a shared library.
  -x <language>            Specify the language of the following input files.
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension.

Options starting with -g, -f, -m, -O, -W, or --param are automatically
 passed on to the various sub-processes invoked by g++.  In order to pass
 other options on to these processes the -W<letter> options must be used.

For bug reporting instructions, please see:
<file:///usr/share/doc/gcc-11/README.Bugs>.

常用选项

选项名作用
-B<directory>将<director>添加到编译器的搜索路径
-v显示编译器调用的程序
-###类似于-v,但选项被引用,命令未被执行
-E仅预处理;不要编译、汇编或链接
-S仅编译;不要组装或连接
-c编译和汇编,但不链接
-o<file>将输出放入<file>。
-shared创建共享库
  -x <language> 

指定以下输入文件的语言。允许的语言包括:c++汇编程序无“none”表示恢复到默认行为

根据文件的扩展名猜测语言。


gcc/g++实战

由于g++和gcc的命令差不多所以下以g++为主

直接生成可执行文件并运行

1:生成可执行文件

首先用vim(可以用其他的编辑器)自己建一个.cpp文件:

root@DESKTOP-S8VRDOE:~/c++# vim hello_world.cpp

写上代码:

退出vim,使用g++编译.cpp

g++ hello_world.cpp

 此时就会发现目录下有一个新文件:a.out ,这个文件就是刚刚生成的可执行文件

root@DESKTOP-S8VRDOE:~/c++# g++ hello_world.cpp
root@DESKTOP-S8VRDOE:~/c++# ll
total 16
drwxr-xr-x 1 root root   512 Oct 22 08:00 ./
drwx------ 1 root root   512 Oct 22 08:00 ../
-rwxr-xr-x 1 root root 16384 Oct 22 08:00 a.out*
-rw-r--r-- 1 root root    91 Oct 22 08:00 hello_world.cpp

(2)运行可执行文件

运行可执行文件:

./a.out

 现在就可以看到可执行文件的输出了

root@DESKTOP-S8VRDOE:~/c++# ./a.out
hello world

分过程生成可执行文件并运行

先同上方一致,创立.cpp文件:hello_world.cpp

(1)预处理

g++ -E hello_world.cPP //如果我们直接执行该命令,预处理的结果会打印在屏幕上。
g++ -E hello_world.cpp -o hello_world.i //我们可以将预处理的结果放到test.i文件中

注意,必须放入test.i中,因为在下一步编译的过程中,指令只能处理.i的文件。

-E指令的含义是:翻译进行到预处理之后停止。

这时就会生成一个hello_world.i文件

root@DESKTOP-S8VRDOE:~/c++# ll
total 848
drwxr-xr-x 1 root root    512 Oct 22 08:12 ./
drwx------ 1 root root    512 Oct 22 08:00 ../
-rwxr-xr-x 1 root root  16384 Oct 22 08:00 a.out*
-rw-r--r-- 1 root root     91 Oct 22 08:00 hello_world.cpp
-rw-r--r-- 1 root root 778705 Oct 22 08:12 hello_world.i

此时查看下hello_world.i文件

 此时可以发现,头文件已经展开

(2)编译

g++ -S hello_world.i

这里就不用指定文件了,它会自动生成一个.s文件

编译时将源代码转换成汇编语言,生成.s文件:

root@DESKTOP-S8VRDOE:~/c++# g++ -S hello_world.i
root@DESKTOP-S8VRDOE:~/c++# ll
total 852
drwxr-xr-x 1 root root    512 Oct 22 08:23 ./
drwx------ 1 root root    512 Oct 22 08:00 ../
-rwxr-xr-x 1 root root  16384 Oct 22 08:00 a.out*
-rw-r--r-- 1 root root     91 Oct 22 08:00 hello_world.cpp
-rw-r--r-- 1 root root 778705 Oct 22 08:12 hello_world.i
-rw-r--r-- 1 root root   2108 Oct 22 08:23 hello_world.s

我们可以打开.s文件查看一下汇编代码:

 (3)汇编

名为汇编,实际上就是将汇编代码转换为计算机可以读懂的机器码:

g++ -c hello_world.s

此时会形成一个二进制文件hello_world.o,但是当打开它时我们看到的是一个乱码状态,我们需

要使用二进制的形式来进行打开:

od hello_world.o

 此时我们就可以看到对应的机器码了。
注意即使计算机可以看懂这些二进制编码,但是我们依然不能通过./来执行这个二进制文件。该文件被称为:可重定向目标文件

(4)链接

g++ hello_world.o

此时生成了可执行文件 a.out

root@DESKTOP-S8VRDOE:~/c++# g++ hello_world.o
root@DESKTOP-S8VRDOE:~/c++# ll
total 872
drwxr-xr-x 1 root root    512 Oct 22 08:31 ./
drwx------ 1 root root    512 Oct 22 08:00 ../
-rwxr-xr-x 1 root root  16384 Oct 22 08:31 a.out*
-rw-r--r-- 1 root root     91 Oct 22 08:00 hello_world.cpp
-rw-r--r-- 1 root root 778705 Oct 22 08:12 hello_world.i
-rw-r--r-- 1 root root   2560 Oct 22 08:28 hello_world.o
-rw-r--r-- 1 root root   2108 Oct 22 08:23 hello_world.s

(5)运行可执行文件

运行可执行文件:

./a.out

 现在就可以看到可执行文件的输出了!

好啦,文章到这里就结束了,还有一些其他的内容之后会慢慢添加

如果喜欢,请给个赞再走呗!(暗示三连)


作者:玄予

来源:CSDN 

链接:Linux下编译工具:gcc/g++ の最全使用教程_玄予的博客-CSDN博客

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章:

  • 【计算机视觉】imutils的基本使用
  • Vue--nextTick--作用/用法/原理
  • 自动化测试项目学习笔记(五):Pytest结合allure生成测试报告以及重构项目
  • 计算机网络习题答案
  • js中的‘==‘和‘===‘
  • 一起来部署项目-采购一台云服务器
  • 【老生谈算法】matlab实现抽样定理算法源码——抽样定理
  • [从0开始机器学习]4.线性回归 正规方程
  • RayVentory以改进IT的分析,RayVentory原始数据之间轻松切换
  • Oracle 递归案例
  • Python编程 print输出函数
  • WordPress JSON REST API OAuth 1.0 认证获取Authorization Basic 码+Python api 创建文章(一)
  • 力扣 每日一题 1235. 规划兼职工作【难度:困难,rating: 2022】(动态规划+二分查找)
  • 数据挖掘-模型的评估(四)
  • 开源远程桌面软件_RustDesk_(可自建远程桌面服务器)
  • axios 和 cookie 的那些事
  • css选择器
  • express如何解决request entity too large问题
  • Golang-长连接-状态推送
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • Linux快速配置 VIM 实现语法高亮 补全 缩进等功能
  • Mysql数据库的条件查询语句
  • ng6--错误信息小结(持续更新)
  • Python利用正则抓取网页内容保存到本地
  • redis学习笔记(三):列表、集合、有序集合
  • REST架构的思考
  • springboot_database项目介绍
  • 闭包,sync使用细节
  • 初识MongoDB分片
  • 飞驰在Mesos的涡轮引擎上
  • 前端自动化解决方案
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 问题之ssh中Host key verification failed的解决
  • shell使用lftp连接ftp和sftp,并可以指定私钥
  • ​secrets --- 生成管理密码的安全随机数​
  • !! 2.对十份论文和报告中的关于OpenCV和Android NDK开发的总结
  • #我与Java虚拟机的故事#连载12:一本书带我深入Java领域
  • (02)Cartographer源码无死角解析-(03) 新数据运行与地图保存、加载地图启动仅定位模式
  • (Matalb时序预测)WOA-BP鲸鱼算法优化BP神经网络的多维时序回归预测
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (接口封装)
  • (免费领源码)Java#ssm#MySQL 创意商城03663-计算机毕业设计项目选题推荐
  • (一)python发送HTTP 请求的两种方式(get和post )
  • (转)c++ std::pair 与 std::make
  • *Algs4-1.5.25随机网格的倍率测试-(未读懂题)
  • .NET Core中Emit的使用
  • .NET NPOI导出Excel详解
  • .NET 药厂业务系统 CPU爆高分析
  • .Net 转战 Android 4.4 日常笔记(4)--按钮事件和国际化
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • .NET开源快速、强大、免费的电子表格组件
  • .net企业级架构实战之7——Spring.net整合Asp.net mvc
  • @Transactional类内部访问失效原因详解
  • [ IO.File ] FileSystemWatcher
  • []新浪博客如何插入代码(其他博客应该也可以)