what happens if an #include fails to find file

2019-09-20 10:05发布

Say I have this very basic c++ code:

myCode.cpp:

#include <library1.h>
#include <library2.h>

int main() {
 // use some methods from library2
}

What will happen if I compile this code but my compiler can't find library1.h? Will it throw any specific error? Will it still look for library2.h? Will it skip the rest of the #include statements and go on to compiling main? I'm asking because I'm trying to answer this SO question where adding one .h file is causing the compiler to complain about not finding methods from another .h file . Without the #include first .h line, the code compiles correctly.

标签: c++ include
3条回答
Evening l夕情丶
2楼-- · 2019-09-20 10:38

When the compiler reaches an include error it reports it and stops the compilation. Of course it may be the case that not all compilers will report a human friendly error, but for sure they all will terminate as this error is fatal as syam points out in his comment.

查看更多
ら.Afraid
3楼-- · 2019-09-20 10:52

Precisely, if it can't find the file then the compiler won't be able to run the program IF it was needed to run your code correctly. If your code accesses something from that file, the program wont run as needed.

查看更多
Root(大扎)
4楼-- · 2019-09-20 10:53

If a specific #include file can't be found, the compilation fails and stops with an error. Compilation can't proceed any further.

Funnily enough, the behaviour in case of a missing header is not explicitly specified. The only relevant part in the Standard is 16.2/1 [cpp.include]:

A #include directive shall identify a header or source file that can be processed by the implementation.

Note the use of shall which gives no choice to the compiler: it must replace the #include directive by the contents of the file. If the file doesn't exist, the program is ill-formed.

查看更多
登录 后发表回答