使用 make 命令构建 c 项目的简略笔记

108 阅读1分钟

项目结构

src
    |- hello1.c
    |- utils.c
    |- Makefile
    |- api.h

Makefile 文件

Makefile 是由 GNU Make 工具解析执行的配置文件,依赖 make 命令。

Makefile 由一系列规则组成,每个规则由 target、prerequisites(可选) 和 commands组成。

  • target 规则的目标,生成文件或执行操作
  • prerequisites(可选),依赖文件或是其他的规则
  • commands,执行的命令

语法格式:

target: prerequisites
    commands
# 注意,上述缩进为TAB键缩进

上述项目结构中的 Makefile 内容:

# make hello -f Makefile -C src
# make clean

hello: hello1.o utils.o
	gcc hello1.o utils.o -o hello

hello1.o: hello1.c
	gcc -c hello1.c

utils.o: utils.c
	gcc -c utils.c

clean: 
	rm -rf *.o

构建

在工程根路径执行命令:

make -C src

未指定规则,默认执行文件中第一个规则 clean; 因为规则 clean 依赖规则 hello,而规则 hello 依赖规则 hello1.o规则 utils.o; 所以才能依序执行。

参考资料

其他资料

备注

// api.h
int add_int(int num1, int num2);
// utils.c
int add_int(int num1, int num2) {
    if (num1 <= 0) {
        num1 = 1;
    }
    if (num2 <= 0) {
        num2 = 1;
    }
    return num1 + num2;
}
// hello1.c
#include <stdio.h>
#include "api.h"

int main() {
    printf("Hello Clang\n");
    printf("add sum = %d\n", add_int(2, 4));
    return 1;
}