您的位置:首页 > 运维架构 > Shell

makefile和bash结合编译-执行(入门)

2017-01-19 17:04 232 查看
有一个test.c的源文件,需要编译和运行,可以使用如下的Makefile和脚本来进行操作

//test.c

#include <stdio.h>

int main(int argc, char *argv[])

{

  printf("test ....\n");

  return 0;

}

#Makefile

#Makefile脚本

#Makefile脚本的规范,依赖关系,执行命令

test: test.o

   gcc -o test test.o

test.o:test.c

   gcc -o test.o -c test.c

#Bash自动编译和执行的脚本

#文件名称:make_run.sh

#----------------------------Bash脚本开始-----------------------------------

#! /bin/bash

#校验输入目标是否存在

if [ -z $1 ]

then

 echo "usage: make_run.sh <compile_file>"

 echo "------compile and run-----------"

 exit -1

fi

#如果目标文件(可执行文件)的日期比源文件*.c文件的日期老,或者文件不存在,则重新make编译生成

cfile="$1.c"

echo "源文件是:$cfile"

if [ $1 -ot $cfile ] || [  -e $1 ]

then

  #编译目标

 make $1

 #如果目标文件不存在,编译失败,则报错

 if [ ! -e $1 ]

 then

  echo "$1生成失败"

  exit -2

  #生成成功

 else

    #检查文件是否具备可执行权限,如果没有则修改权限

   if [ !  -x $1 ]

   then

     chmod +x $1

   fi

   #编译执行成功,直接运行目标程序

   ./$1

 fi

fi

#----------------------------Bash脚本结束-----------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bash linux makefile