c - #included 文件的优先级

标签 c gcc include

当使用带有-I 选项的gcc 时,要搜索的目录的优先级是什么?如果您的 header 名称与系统 header 的名称冲突,但它们位于不同的目录中怎么办?哪一个将被 #include 编辑?另外,系统 header 的顺序是什么?

最佳答案

这是一个中等复杂的问题,取决于您是否写了 #include <header.h>#include "header.h"以及所包含的文件是直接从您的来源包含还是由另一个 header 包含。

通常,双引号中的名称在包含 header 源文件的目录中查找,然后在与搜索尖括号中的名称相同的位置(因此 #include "header.h" 查找的位置比 #include <header.h> 查找的位置多).

您可以添加更多使用 -I /some/other/include 搜索的地点命令行选项。这些按顺序在系统(默认)位置之前搜索。搜索的系统位置可能因平台而异。在 Unix 上,它通常包括 /usr/local/include并始终以 /usr/include 结尾;它也可以包括其他地方。

如果#include行在另一个 header 中,GCC 开始在找到第一个 header 的目录中搜索该嵌套 header ,而不是从头开始重新启动。

对于某些平台上的某些系统 header ,GCC 创建了 header 的第二个固定副本,用于代替 /usr/include 中的 header 。或其下界。

您可以使用命令行选项覆盖大部分这些行为。有关完整的详细信息,请阅读 GCC [预处理器] 手册,了解它如何处理 Header Files . GCC 编译器手册在 Preprocessor Options 中概述了控制它的选项。手册的一部分。预处理器手册在 Invocation 中列出了深奥的选项.

例子

表明“当前目录”是“包含源文件的目录”。

$ mkdir x3
$ echo 'Code from x3/header1.h' > x3/header1.h
$ echo '#include "header1.h"'   > x3/source.c
$ echo 'This is from the current directory, not from the subdirectory.' > header1.h
$ cpp x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "x3/header1.h" 1
Code from x3/header1.h
# 1 "x3/source.c" 2
$ cpp -I . x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "x3/header1.h" 1
Code from x3/header1.h
# 1 "x3/source.c" 2
$ rm x3/header1.h
$ cpp x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
x3/source.c:1:21: fatal error: header1.h: No such file or directory
 #include "header1.h"
                     ^
compilation terminated.
$ cpp -I . x3/source.c
# 1 "x3/source.c"
# 1 "<command-line>"
# 1 "x3/source.c"
# 1 "./header1.h" 1
This is from the current directory, not from the subdirectory.
# 1 "x3/source.c" 2
$ rm -fr header1.h x3
$

使用 cpp 测试来自 Mac OS X 10.9.2 上的 GCC 4.8.2。

关于c - #included 文件的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271734/

相关文章:

c - 在 C 中打印系统名称?

c++ - VS2015 和 GCC 5.4.0 中的 Constexpr 阶乘编译结果

c++ - 尝试在 Xcode 中包含一个库,找不到文件

c - 如何编译 MEX 文件

c++ - 函数参数中的按位或 (|)

c - GCC 中没有参数检查

android - 为什么 gcc emmiting 代码与 ARM 指令集的 2 字节边界对齐?

php - 如何在 zend 框架项目中包含 inc.php 文件?

C++:文件与自身冲突

c++ - 将正符号变量替换为无符号变量