简体   繁体   中英

Do all “.h” header files that are #include-ed have to be in the same folder as your .cpp file?

I'm working on a larger project, and a lot of the .cpp files are including files that are in different directories, but there are no references of accessing other directories in the code.

Thanks for the help.

No.

Usually you give the compiler (or, more specifically, the preprocessor) a bunch of include directories, to tell it where to look for header files. This is typically done from the Makefile (or from the project settings when building inside an IDE).

Exactly how the option looks is of course up to each compiler. With gcc, it's the -I option .

As far as I'm concern you can have the .h and .cpp files in different directories. Suppose you have a folder for headers and one for .cpps. In you cpp files you just #include "headers/myheader.h" and should perfectly work.

否。除了提到的-I编译器选项外,您还可以在#include指令的filename参数中使用(通常是相对的)path-spec。

For:

#include "header.h"

The compiler (or more strictly the pre-processor) will look first in the folder of the including source file, then through a list of files specified in some compiler dependent form - usually command line options and/or environment variables.

For:

#include <header.h> 

the folder of the including source is not searched, and only the list of paths specified to the compiler are searched.

GCC actually has three search groups:

  • current source file path
  • quote include directories
  • system include directories

Quoted headers search all three in that order, while <header.h> type inclusions searches only the last. Not all compilers are that specific about what constitutes a "system include" and the last two are not distinguished and are specified in the same manner.

Your compiler should document the actual behaviour, for GCC for example see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM