跟我一起写Makefile

在跟我一起写Makefile中使用的时GNU make,在这里我用的是codeblocks中带的mingw32-make进行的相关操作。

makefile内的命令格式大致为

target: preprerequisite

[Tab]command

首先先接触一个简单的例子。

  1. 在相关c文件夹中创建相关的头文件和C文件,如:make_test/hello.h, make_test/hello.c make_test/main.c make_text/makefile.txt(或者makefile),其相应代码为:

   hello.h

#ifndef HELLO_H
#define HELLO_H
#include<stdio.h>
void printf_hello();
#endif // HELLO_H

    hello.c

#include"hello.h"


void printf_hello(){
    printf("printf hello");
}

    main.c

#include"hello.h"
#include<stdio.h>
int main(void){
    printf_hello();
    return 0;
}

    makefile.txt(或者makefile)

main.exe: main.o hello.o
    gcc -o main.exe main.o hello.o
hello.o: hello.c hello.h
    gcc -c hello.c
main.o: main.c
    gcc -c main.c

.PHONY: clean
clean:
    -del hello.o main.o

在make_test文件夹下打开命令行终端进行如下操作

      mingw32-make --file makefile.txt main.exe

该命令可以生成相应的中间文件和最终的可执行文件

      mingw32-make --file makefile.txt .PHONY

该命令可以删除相应的中间文件。

对于上述的makefile有点复杂当然我们可以添加一些变量进行代换,如:

obj_name = main.o hello.o
main.exe: main.o hello.o
    gcc -o main.exe main.o hello.o
hello.o: hello.c hello.h
    gcc -c hello.c
main.o: main.c
    gcc -c main.c

.PHONY: clean
clean:
    -del $(obj_name)

将其中的main.o 和hello.o用变量obj_name进行代换调用命令 mingw32-make --file makefile .PHONY也是可以完成相应的删除工作

当然利用make工具的隐晦规则也是可以的,该隐晦规则为相应的目标文件会扩展添加target_name.c,如

obj_name = main.o hello.o
main.exe: main.o hello.o
    gcc -o main.exe main.o hello.o
hello.o: hello.h
    gcc -c hello.c
main.o:
    gcc -c main.c

.PHONY: clean
clean:
    -del $(obj_name)
原文地址:https://www.cnblogs.com/hebust-fengyu/p/10650918.html