1. 程式人生 > >Linux 中C/C++ search path(標頭檔案搜尋路徑)

Linux 中C/C++ search path(標頭檔案搜尋路徑)

起因

我拿到了一套Linux下的C++程式碼,程式碼中有這個標頭檔案#include <unistd.h>,在Windows上檢視缺少這個標頭檔案,而這個標頭檔案就是Linux中的系統檔案。

困惑

因此我想在Linux下去查詢這個檔案。通過Linux指令:

locate unistd.h

查詢結果下圖所示:
圖一

查找出來這麼多路徑下的同名檔案,不知道要用哪一個unistd.h。因此必須要找g++或者gcc標頭檔案搜尋路徑。

方法

Search Path

By default, the preprocessor looks for header files included by the quote form of the directive #include “file” first relative to the directory of the current file, and then in a preconfigured list of standard system directories. For example, if /usr/include/sys/stat.h contains #include “types.h”, GCC looks for types.h first in /usr/include/sys, then in its usual search path.

For the angle-bracket form #include , the preprocessor’s default behavior is to look only in the standard system directories. The exact search directory list depends on the target system, how GCC is configured, and where it is installed. You can find the default search directory list for your version of CPP by invoking it with the -v option. For example,

cpp -v /dev/null -o /dev/null

There are a number of command-line options you can use to add additional directories to the search path. The most commonly-used option is -Idir, which causes dir to be searched after the current directory (for the quote form of the directive) and ahead of the standard system directories. You can specify multiple -I options on the command line, in which case the directories are searched in left-to-right order.

If you need separate control over the search paths for the quote and angle-bracket forms of the ‘#include’ directive, you can use the -iquote and/or -isystem options instead of -I. See Invocation, for a detailed description of these options, as well as others that are less generally useful.

If you specify other options on the command line, such as -I, that affect where the preprocessor searches for header files, the directory list printed by the -v option reflects the actual search path used by the preprocessor.

Note that you can also prevent the preprocessor from searching any of the default system header directories with the -nostdinc option. This is useful when you are compiling an operating system kernel or some other program that does not use the standard C library facilities, or the standard C library itself.

解決

我在Linux終端執行了這條指令:

cpp -v /dev/null -o /dev/null

顯示效果如圖所示:
圖二

最後我根據之前locate unistd.h查詢到的路徑(看圖一),比對圖二中的路徑,確定就能在/usr/include路徑下,找到我想要的unistd.h檔案。