第二章Linux下C语言开发工具
第二章 Linux下C语言开发工具
两个重点:VIM编辑器;GCC/GDB编译调试工具
2.1 常用编辑工具
vim Emacs
2.1.1 VIM编辑工具
- 编写源程序:
[root@localhost~]#vim hello.c
- 三种模式切换:
2.2 GCC/GDB编译调试工具基础
GCC/G++ 是GNU最优秀的自由软件之一,它主要提供C/C++程序的编译工作。LInux下的C、C++程序开发过程中,一般都采用GCC/G++/GDB工具。
- 将C语言程序编译成一个可执行文件一般都需经过以下四个步骤:
(1)预处理(Preprocessing): 预处理器,对源代码文件中的文件包含、宏定义、预编译语进行分析和替换。 展开头文件、宏替换、去掉注释行
(2)编译(Compilation):根据编译器的语法规则,将高级语言转换为以.s为后缀的汇编语言文件。 .s 汇编文件
(3)汇编(Assembly): 汇编器,将.S和.s为后的汇编语言文件经过预编译和汇编成为以.o为后缀的目标文件。.o 二进制文件
(4)连接(Linking): 链接器,当所有的目标文件都生成之后,将它们安排到可执行程序中恰当的位置上,同时,该程序所调用到的库函数也需要连接到合适的地方。
文件名后缀 | 说明 | gcc参数 |
---|---|---|
.c | 源文件 | 无 |
.i | 预处理后的C文件 | -E |
.s | 编译之后得到的汇编语言的源文件 | -s |
.o | 汇编后得到的二进制文件 | -c |
连接 | -o |
**实操:**使用gcc编译hello.c文件
// 用vim创建的hello.c
#include<stdio.h>
int main(void)
{
printf("hello world!\n");
}
gcc编译:
(1) 直接用gcc -c 编译代码,得到.o文件。(包含了-E的预处理和-s的汇编操作)
[chen@localhost ~]$ gcc -c hello.c
//
查询文件
[chen@localhost ~]$ ls
hello.c hello.o
(2) 用 gcc -o 命令连接成可执行程序
第一次操作报错:
[chen@localhost ~]$ gcc -o hello.c
报错信息:
gcc:致命错误:没有输入文件
编译中断。
错误原因:编译的指令格式使用错误。修改为以下正确
// gcc .c文件名 -o 可执行程序名
[chen@localhost ~]$ gcc hello.c -o hello
[chen@localhost ~]$ ls
hello.c hello.o hello
//执行 可执行程序 hello
[chen@localhost ~]$ ./hello
hello world!
g++编译:
(0)用vim创建一个.C的C++文件 hello plus.C
[chen@localhost ~]$ vim helloplus.C
//内容 cout和endl需要加std::;include中不能加.h
#include<iostream>
int main(int argc,char**argv)
{
std::cout<<"Hello,C++ world"<<std::endl;
return 0;
}
(1) -c 编译 生成-o ;然后 g++ -o helloplus hellplus.o
[chen@localhost ~]$ g++ -c helloplus.C
[chen@localhost ~]$ ls
helloplus.C helloplus.o
[chen@localhost ~]$ g++ -o helloplus helloplus.o
[chen@localhost ~]$ ls
helloplus helloplus.C helloplus.o
(2) 直接-o一步完成 : g++ -o hello2 helloplus.Cvim
[chen@localhost ~]$ g++ -o hello2 helloplus.C
[chen@localhost ~]$ ls
hello2 helloplus helloplus.C helloplus.o
! -o使用时的格式:
g++ -o 先可执行程序名(自己设置,可与文件名不同) 再.c或者.o文件名(可以不止一个文件,用空格隔开即可) |
---|
GDB调试:利用GDB工具查找程序中出现的问题
创建bug.c文件:
#include<stdio.h>
#include<stdlib.h>
static char buff[256];
static char* string="\0";
int main()
{
printf("Please input a string:");
gets(string);
printf("\nYour string is: %s\n",string);
}
报错:
//执行命令 $ gcc -o bug -ggdb bug.c
bug.c: 在函数‘main’中:
bug.c:8:2: 警告:不建议使用‘gets’(声明于 /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(string);
GDB的命令
(1)运行 gdb bug命令,装入bug可执行文件
//
[chen@localhost ~]$ gdb bug
(2)使用 list命令查看代码
(gdb) list
(3)使用run命令执行程序
(gdb) r
(4)使用where命令产看程序出错位置
(gdb) where
PS:以上代码错误的原因是 gets获得的值为 const char*,string的类型时char* ,不能把const char* 赋给string;
可修改成,用char buff[]接收gets获得值,然后用 string =(char*) buff; 获得值
printf("Please input a string:");
gets(buff);
string =(char*) buff; // string =buff;也可以
printf("\nYour string is: %s\n",string);