ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序

1、在Ubuntu系统下用C语言编写一个简单的输出 hello word 的程序,并编译有、运行之;
2、请编写一个主程序文件 main1.c 和一个子程序文件 sub1.c, 要求:子程序sub1.c 包含一个算术运算函数 float x2x(int a,int b),此函数功能为对两个输入整型参数做某个运算,将结果做浮点数返回;主程序main1.c,定义并赋值两整型变量,然后调用函数 x2x,将x2x的返回结果printf出来。
1) 请在ubuntu系统用gcc 命令行方式编译主程序main1.c 并运行;
2) 请在windows系统下用你熟悉的编译工具编译主程序main1.c 并运行。
3、在任务4基础上,在ubuntu系统下用Makefile方式编程主程序。
一、gcc编译c程序。
1、以hello world为例子:
先使用ctrl+alt+t打开终端,输入vim hello.c创建一个c程序,回车进行编写,先输入i进入编写模式,然后编写好程序 按下esc,退出输入模式,在按住shift+:在输入wq,回车保存程序退出
#include
int main()
{
printf("hello world!!\n");
return 0;
}
最后输入gcc hello.c -o hello回车在输入./hello即可
ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片


ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片

gcc的编译过程:
预处理gcc -E hello.c -o hello.i编译器将源代码中包含头文件编译进来
编译gcc -S hello.i -o hello.s检查代码规范性并翻译成汇编语言
汇编gcc -c hello.s -o hello.o将.s文件转换为目标文件
链接gcc hello.o -o hello将目标文件转换为可执行文
2、编写mian1.c程序和sub1.h程序
main1.c:
#include
#include"sub1.h"
int main()
{int a,b;
double y;
a=6,b=9;
y=x2x(a,b);
printf("%f",y);
return 0;
}
sub1.h:
#include
float x2x(int a,int b)
{
float x;
x=a+b;
return x;
}
ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片





3、与Windows上编译器进行对比:
ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片

ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片

ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片

二、使用Makefile编译c程序
makefile的编写规则
target:prerequisites
command# command以一个tab键开始
# target为一个目标文件,可以是Object File,也可以是执行文件。还可以是一个标签(Label)
# prerequisites是需要生成target所依赖的文件或是目标
# command也就是make需要执行的命令。(任意的Shell命令)

创建Makefile文件:
gedit makefile进入编辑
main: main1.o
gcc main1.o -o main
main: main1
gcc -c main1.c
clean:
rm -rf *.o main
在输入gcc main1.o -o mian
在输入./main 即可
ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序
文章图片

三、总结,学会了简单的vim 和grdit的简单编辑指令,然后学会了makefile和gcc对于c程序的编译。对于整个c程序的编译运行过程有了一个更加深入的了解。

【ubuntu|Ubuntu系统里使用gcc和Makefile编译c程序】

    推荐阅读