C语言Makefile文件使用

C语言中代码Makefile文件的写法

单文件,例:

#定义变量

CFLAGS=gcc

 

#具体命令都需要一个入口,all: 这个就相当于入口,默认情况,执行第一次入口,

#后面执行其他入口进行依赖,如果依赖入口未执行过,那么,先执行依赖入口,否则,不用执行

all: cp run

 

cp:

@echo "编译文件开始"

$(CFLAGS) -o test test.c

@echo "编译文件结束"

 

#在这样的情况下,cp只执行了一次

run: cp

@echo "运行开始"

@./test

@echo "运行结束"

 

特别注意:这里Makefile文件中,文件不认空格,只能使用制表符[tab],

如果使用了入口,那么,必须下一行需要使用制表符[tab]来进行处理

 

多文件,例:

test.c 

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
  printf("hello world\n");
  exit(0);
}

 

 

当C存在头文件和文件间的引用的时候,

示例代码:

  test01.h(定义函数名称,后续直接引用该文件名就可以指向对应的实际方法中)

  

#ifndef TEST01_H
#define TEST01_H

#include <stdbool.h>
#include <unistd.h>

void test_init();
#endif

 

  test01.c

  

#include <stdlib.h>
#include <stdio.h>
#include "test01.h"

void test_init() {
    printf("test01, test!");
    exit(0);
}

 

  test02.c

#include <stdio.h>
#include "test01.h"

int main(int argc, char **argv) {
    test_init();
}

 

编译命令:

  gcc test01.c test02.c -o test02.out

运行命令:

  ./test02.out

结果:

  test01, test!

  

多文件也是可以使用Makefile方式进行管理的,具体的方式,将对应的命令替换掉就可以了。

 

posted on 2016-09-12 14:08  舒润  阅读(1042)  评论(0编辑  收藏  举报

导航