include包含文件查找的順序


從microsoft網站上找到關於#include Directive (C/C++)的相關問題解釋如下:

The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears.

 

Syntax Form

Action

Quoted form

The preprocessor searches for include files in the following order:

  1. In the same directory as the file that contains the #include statement.

  2. In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first.

  3. Along the path specified by each /I compiler option.

  4. Along the paths specified by the INCLUDE environment variable.

Angle-bracket form

The preprocessor searches for include files in the following order:

  1. Along the path specified by each /I compiler option.

  2. When compiling from the command line, along the paths that are specified by the INCLUDE environment variable.

按照上述,二者的區別在於:當被include的文件路徑不是絕對路徑的時候,有不同的搜索順序。對於使用雙引號“”包含的include文件,搜索的時候按以下順序:

 

1.在包含當前include指令的文件所在的文件夾內搜索;

2.如果上一步找不到,則在之前已經使用include指令打開過的文件所在的文件夾內搜索,如果已經有多個被include的文件,則按照它們被打開的相反順序去搜索;

3.如果上一步找不到,則在編譯器設置的include路徑內搜索;

4.如果上一步找不到,則在系統的INCLUDE環境變量內搜索。

而對於使用半角尖括號<>包含的include文件,搜索的時候按以下順序:

1.在編譯器設置的include路徑內搜索;

2.如果是在命令行中編譯,則在系統的INCLUDE環境變量內搜索。

對於非絕對路徑的文件使用上述兩種include指令搜索時,一旦找到include命令所指定的文件,編譯器就停止搜索。但是如果被include的文件是絕對路徑的文件,比如 #include "D:\Program Files\OpenCV1.0\cv\include\cv.h" ,被包含的cv.h文件路徑是絕對路徑,這種情況下編譯器直接按照這個給出的絕對路徑是搜索。

以下為一個使用尖括號<>include的例子:

#include <stdio.h>

在這個例子里,我們向源程序代碼中包含stdio.h文件,由於使用的是尖括號<>,預處理器搜索的時候,先在編譯器設置的include路徑內搜索,如果找不到,就在系統的INCLUDE環境變量內搜索。

以下為一個使用雙引號" "include的例子:

 

    #include "defs.h"
在這個例子里,我們向源程序代碼中包含defs.h文件,由於使用的是雙引號" ",預處理器搜索的時候,使用了這條指令的父文件所在文件夾內搜索,所謂的父文件,就是這條include指令所在的文件,如果找不到,在父文件的父文件所在文件夾內搜索,如果仍然找不到,則在編譯器設置的include路徑內搜索,如果還找不到,就在系統的INCLUDE環境變量內搜索。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM