Skip to content

LV080-文件包含

本文主要是makefile——文件包含和嵌套执行相关笔记,若笔记中有错误或者不合适的地方,欢迎批评指正😃。

一、文件准备

1. 目录结构

各文件所在目录的结构如下:

c
.
├── main.c
├── Makefile
├── test1.c
├── test1.h
├── test2.c
└── test2.h

0 directories, 6 files

2. 源码

2.1 main.c

c
#include <stdio.h>
#include "test1.h"
#include "test2.h"

int main(int argc, const char *argv[])
{
	printf("This is main file!\n");
	test1Fun();
	test2Fun();
	return 0;
}

2.2 test1.c

c
#include <stdio.h>

void test1Fun()
{
    printf("This is test1.c file\n");
}

2.3 test2.c

c
#include <stdio.h>

void test2Fun()
{
    printf("This is test2.c file\n");
}

2.4 test1.h

c
#ifndef __TEST1_H__
#define __TEST1_H__

void test1Fun();

#endif

2.5 test2.h

c
#ifndef __TEST2_H__
#define __TEST2_H__

void test2Fun();

#endif

二、文件包含

像 C 语言一样,在 Makefile 中使用 include 关键字可以把别的 Makefile 包含进来。

1. 使用格式

使用格式如下:

shell
include <filename>

【注意】

(1)在 include 前面可以有一些空字符,但是绝不能是 Tab 键开始。若要包含的多个文件,这些文件之间要使用空格分隔开。

(2)使用 include 包含进来的 Makefile 文件中,如果存在函数或者是变量的引用,它们会在包含的 Makefile 中展开。

(3)使用 include <filenames> , make 在处理程序的时候,文件列表中的任意一个文件不存在的时候或者是没有规则去创建这个文件的时候, make 程序将会提示错误并保存退出。

2. 搜索路径

当 make 读取到 include 关键字的时候,会暂停读取当前的 Makefile ,而是去读 include 包含的文件,读取结束后再继读取当前的 Makefile 文件。如果文件都没有指定绝对路径或是相对路径的话, make 会在当前目录下首先寻找,如果当前目录下没有找到,那么, make 还会在下面的几个目录下找:

(1)如果 make 执行时,有 -I 或 --include-dir 参数,那么 make 就会在这个参数所指定 的目录下去寻找。

(2)如果目录 /include (一般是: /usr/local/bin 或 /usr/include )存在的话, make 也会在这些文件夹下寻找文件。

如果有文件没有找到的话, make 会生成一条警告信息,但不会马上出现致命错误。它会继续载入其它的文件,一旦完成 Makefile 的读取, make 会再重试这些没有找到,或是不能读取的文件。如果还是不行, make 才会出现一条致命信息。

3. 忽略错误

如果想让 make 不理那些无法读取的文件,而继续执行,我们可以在 include 前加一个减号 - 。

shell
-include <filename>

这就表示,无论过程中出现什么错误,都不要报错继续执行。和其它版本 make 兼容 的相关命令是 sinclude ,其作用相同。