Linux 中C/C++ search path(头文件搜索路径)

时间:2021-11-25 22:56:50

https://blog.csdn.net/BjarneCpp/article/details/76135980

起因

我拿到了一套Linux下的C++代码,代码中有这个头文件#include <unistd.h>,在Windows上查看缺少这个头文件,而这个头文件就是Linux中的系统文件。

困惑

因此我想在Linux下去查找这个文件。通过Linux指令:

locate unistd.h

查找结果下图所示: 
Linux 中C/C++ search path(头文件搜索路径)

查找出来这么多路径下的同名文件,不知道要用哪一个unistd.h。因此必须要找g++或者gcc头文件搜索路径。

方法

我在这里 C/C++ search path(头文件搜索路径) - MJN - CSDN博客 找到了办法。

这里 GCC The C Preprocessor: Search Path 讲述了如何去查看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

显示效果如图所示: 
Linux 中C/C++ search path(头文件搜索路径)

最后我根据之前locate unistd.h查找到的路径(看图一),比对图二中的路径,确定就能在/usr/include路径下,找到我想要的unistd.h文件。