基于Ubuntu系统下使用gcc和Makefile编译C语言程序

写在前面:
本文是以完成嵌入式系统程序设计基础为目的,若有不足之处望大家见谅。

程序要求:编写一个主程序文件 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 并运行。在其基础上,在ubuntu系统下用Makefile方式编程主程序。
    ———————————————————————————————

一、使用gcc编译

tips:
vi + xx名称 进入xx文件的编辑模式
进入编辑模式后按 【i】键即可以开始编辑
编辑完毕后按ESC键,再输入(:wq)冒号不能掉;

1、gcc调试:输出Hello world
输入 vim Hello.c 进入编写程序界面:
基于Ubuntu系统下使用gcc和Makefile编译C语言程序
按ESC(进入命令行模式),然后输入”:wq”,冒号表示开始输入命令,字母w代表保存文件,字母q代表退出编辑器:

编译Hello.c 命令如下:

gcc -c Hello.c
gcc -o Hello Hello.o
./Hello

执行后正确输出:基于Ubuntu系统下使用gcc和Makefile编译C语言程序

2、实验案例

如上所示编写sub1.h:

#ifndef __SUB1_H
#define __SUB1_H
#include<stdio.h>
float x2x(int a,int b);       
#endif

编写sub1.c

#include "sub1.h"
float x2x(int a,int b)
{
	float s;
	s=a+b;
	return s;
}

编写main1.c

#include<stdio.h>
#include"sub1.h"
float x2x(int a,int b);
int main()
{
	int x=4,y=5;
	float c;
	c=x2x(x,y);
	return 0;
 } 

编译过程:

  1. 先输入 gcc -c sub1.c
    将sub1.c文件变成sub1.o目标文件

  2. 再输入 gcc main1.c sub1.o -o main1
    编译main1.c文件为目标文件main1.o,再与sub1.o文件链接,生成main1 可执行文件

  3. 输入./main1
    得到编译结果
    基于Ubuntu系统下使用gcc和Makefile编译C语言程序

二、使用windows系统编译

使用软件:Dev-+
代码如下:

sub1.h

#include<stdio.h>
float x2x(int a,int b)
{
	float s;
	s=a+b;
	return s;
}

mian1.c

#include<stdio.h>
#include"sub1.h"    
void main()
{
  int a=4,b=5;      
  float c;          
  c=x2x(a,b);
  printf("%f\n",c); 
  return 0;
}

编译后结果:
基于Ubuntu系统下使用gcc和Makefile编译C语言程序

三、使用Makefile编译

1)为做实验方便,首先删除.o文件与可执行文件:

rm -f main1.o sub1.o
rm -f example

2)进入makefile编辑:
基于Ubuntu系统下使用gcc和Makefile编译C语言程序
3)保存退出,运行make命令,得到相同输出结果:
基于Ubuntu系统下使用gcc和Makefile编译C语言程序

总结:
通过本次基于Ubuntu系统使用gcc和Makefile进行C语言编译实操,了解并且掌握许多其编译时的语法规则,初步学习并借鉴了一下网上的案例,完成了本次实验;通过分别在Ubuntu系统和Windows系统上进行C语言的编译,发现虽然Windows系统操作更加简便,但是Ubuntu系统更能让我们从底层认识到原始文件是如何一步步变成可执行文件的。
————————————————

参考文献:
https://blog.csdn.net/rzh222/article/details/120254013
https://blog.csdn.net/weixin_51121425/article/details/108804948
https://blog.csdn.net/peishuai1987/article/details/89882956
https://blog.csdn.net/qq_45237293/article/details/108741893

上一篇:Ubuntu下编译c语言程序以及通过使用Makefile进行编译


下一篇:React Hooks 性能优化,带你玩转 Hooks