ubuntu下使用gcc和Makefile编译运行c程序

目录

一:用c语言编写一个简单的helloworld

 二:浮点数输出

vs code输出浮点数

三:使用makefile编译c程序

四:总结

五:借鉴的文章


一:用c语言编写一个简单的helloworld

    在ubuntu终端使用命令 sudo apt-get install vim,安装完后就可以在终端使用vim文本编辑软件来编写c程序。

以helloworld为例,使用命令:

vim hello.c

进入文本编辑器,开始编写c程序 hello world:

#include 
int main(){
   printf("hello world!");
   return 0;
}

注意:在头文件编写的时候,如果写成stdio 可能会报错

 编写完成后,按ESC键, 再输入“:wq”就可以保存文件了

gcc编译hello.c

 

gcc的编译流程:

  1. 预处理,生成预编译文件
    gcc -E hello.c -o hello.i
  2. 编译,生成汇编代码
    gcc -S hello.i -o hello.s
  3. 汇编,生成目标文件
    gcc -c hello.s -o hello.o
  4. 链接,生成可执行文件
    gcc hello.o -o hello

 二:浮点数输出

 编写c程序

1. 编写main1.c

#include"sub1.h"

int main()
{
        int x,y;
         printf("Please input the value of x:");
        scanf("%d",&x0);
        printf("Please input the value of y:");
        scanf("%d",&y); 
        printf("%.2f\n",x2x(x,y));      //输出处理后的值,保留两位小数
        return 0;
}

2. 编写sub1.c

#include "sub1.h"

/*******************/
/*     参数:a,b    */
/*    返回值:ans    */
/*******************/
float x2x(int a,int b)
{
        float ans;
        ans=(float)b/a;
        return ans;
}

3.sub1.h

#ifndef __SUB1_H
#define __SUB1_H

#include

float x2x(int a,int b);         //计算b除以a的结果

#endif

4.gcc直接编译

  • 步骤一

          命令:gcc -c sub1.c

          作用:将sub1.c程序转换为目标文件sub1.o

  • 步骤二

         命令:gcc main1.c sub1.o -o main1

        作用:编译main1.c文件为目标文件main1.o,然后链接sub1.o目标文件生成main1可执行文件

  • 步骤三

          执行./main1命令,即可执行编译生成的main1程序
 

先查看编写ubuntu下使用gcc和Makefile编译运行c程序_第1张图片 的程序  l

 编译

ubuntu下使用gcc和Makefile编译运行c程序_第2张图片

 运行生成的main1 程序

ubuntu下使用gcc和Makefile编译运行c程序_第3张图片

 输出成功!

三:使用makefile编译c程序

Makefile的定义规则
makefile语法:
target表示目标文件,dependent表示依赖文件

target [target…] : [dependent …]
[ command …]
实例:
hello: main.o factorial.o hello.o
$(CC) main.o factorial.o hello.o -o hello

makefile文件内容:

main1:sub1.o main1.o
         gcc main1.c sub1.o -o main1    
 sub1.o:sub1.c
        gcc -c   sub1.c -o sub1.o

clean:
        rm *.o

执行命令  make 即编译得到main1可执行文件

 ubuntu下使用gcc和Makefile编译运行c程序_第4张图片

 运行main1文件

删除编译过程中生成的中间文件,使用命令 make clean

 ubuntu下使用gcc和Makefile编译运行c程序_第5张图片

四:总结

通过这次试验,让我学到了很多知识,首先就是gcc的编译过程,一个c程序要经过预处理、编译、汇编和链接再生成可执行文件,并且编译这些过程都需要我们手动人为地去完成,而不能像windows上vs code那样一键编译运行。而makefile就相当于一个脚本,当我们编写自己地makefile代码后,可以一键编译为可执行文件,帮助我们省去了大量的时间,并且makefile可以适用于一个项目存在较多的源程序,而用gcc编译就可能会出错。

五:借鉴的文章

Ubuntu系统使用gcc和Makefile编译C程序

不同方式不同系统编译main1.c程序

你可能感兴趣的:(ubuntu,c语言,vim)