Featured image of post Makefile入门学习笔记

Makefile入门学习笔记

Makefile快速入门的学习笔记和复习指南

!施工中

学习来源:20分钟Makefile光速入门教程 By: GeekHour
推荐指数:⭐⭐⭐⭐

构建

定义

$$ { \text{源码文件, 资源文件} } \rightarrow \text{可执行文件} $$

过程

$$ { \text{源文件} } \rightarrow { \text{预处理} } \rightarrow { \text{编译} } \rightarrow { \text{汇编} } \rightarrow { \text{链接} } \rightarrow { \text{打包部署} } $$

如何构建

  1. 当单个文件的时,我们可以使用编译命令来构建程序
  2. 当涉及到多个源文件和资源文件时,使用自动化的构建程序是更好的选择

Make学习

访问代码仓库

使用命令编译执行源文件

创建 main.c ,编写一个简单的C程序

1
2
3
4
5
6
#include <stdio.h>

int main(){
    printf("Hello, World!\n");
    return 0;
}

在shell1中输入命令:

1
gcc main.c -o hello

使用GCC2编译器编译main.c源文件,并生成可执行文件

使用./hello运行可执行文件

简单使用Make

  1. 创建头文件message.h
1
void message()
  1. 创建message.c
1
2
3
4
5
#incldue <stdio.h>

void message() {
    printf("Hello, World!\n");
}
  1. 修改main.c
1
2
3
4
5
6
7
8
#include <stdio.h>
#include "message.h"

int main(){
+    message();
-    printf("Hello, World!\n");
    return 0;
}
  1. 添加Makefile
1
2
hello: main.c message.c
    gcc main.c message.c -o hello

Make规范技巧

  1. 分步骤生成可执行文件
1
2
3
4
5
6
7
8
hello: main.o message.o
    gcc main.o message.o -o hello

main.o: main.c
    gcc -c main.c

message.o: message.c
    gcc -c message.c

优点:如果只修改了message.c,那么main.c不会被重新执行

  1. 伪目标
1
2
+ clean:
+   rm -f *o hello

注意:目录下不可以有和伪目标同名的文件


  1. 作者使用Windows 11环境, Shell通常指代“命令提示符”,获取Microsoft官方支持 ↩︎

  2. 关于如何安装GCC环境,作者不再赘述,可以查看FreeCodeCamp-How to Install C and C++ Compilers on Windows ↩︎

Licensed under CC 4.0 BY-SA
使用 Hugo 构建
主题 StackJimmy 设计