Checking header file for dependencies at compile-time

孤街醉人 提交于 2019-12-12 02:30:06

问题


Do compilers offer the capability to automatically check if each source file (and its associated header file, if any) include all other headers that are required? Or at least issue a warning, say, if a required header is not included explicitly?

For example, I would like the compiler to report when I do something like this:

header1.h

#include <string>
...

header2.h

#include "header1.h"
#include <iostream>
std::string blah;    //<-- issue warning here, <string> not included explicitly
...

source2.cpp

#include "header2.h"
...
cout << endl;        //<-- issue warning here, <iostream> not included explicitly

I am using g++ and Visual Studio, so my question primarily applies to these compilers. Thanks!


回答1:


There is no automatic way for doing so, as far as I know.

My suggestion is to confine inclusions into headers only to what is needed for the "interface" defined in the .h In C++ Coding Standards (Sutter, Alexandrescu) you can find an item which tackles this explicitly (it's titled Make header files self-sufficient). I cite:

Behave responsibly: Ensure that each header you write is compilable standalone, by having it include any headers its contents depend upon

and

But don't include headers that you don't need; they just create stray dependencies. Consider this technique to help enforce header self-sufficiency: In your build, compile each header in isolation and validate that there are no errors or warnings.

Moreover you should always include your own .h first, since this maximizes the probability of finding out if there are inclusion errors.

In all cases, headers should be swappable, so that if your file includes a.h and b.h, both possible orders should do.



来源:https://stackoverflow.com/questions/17569023/checking-header-file-for-dependencies-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!