【问题标题】:Priority in which files are #included#included 文件的优先级
【发布时间】:2014-03-08 16:11:54
【问题描述】:

当使用gcc-I 选项时,要搜索的目录的优先级是多少?如果您的标头名称与系统标头的名称冲突,但它们位于不同的目录中怎么办?哪一个是#include-ed?另外,系统头文件包含在什么顺序?

【问题讨论】:

    标签: c gcc include


    【解决方案1】:

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

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

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

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

    对于某些平台上的某些系统头文件,GCC 会创建头文件的第二个固定副本,用于代替 /usr/include 或其下区域中的头文件。

    您可以使用命令行选项覆盖大部分这些行为。有关完整的详细信息,请阅读 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
    $
    

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

    【讨论】:

    • 我的意思是#include
    • 这涉及#include &lt;header.h&gt;;它与#include "header.h" 几乎相同,只是不会首先搜索当前目录,除非您通过-I . 添加它。
    【解决方案2】:

    顺序。文件出现的第一个。

    就像PATH 变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多