在编译时检查头文件的依赖关系 [英] Checking header file for dependencies at compile-time

查看:767
本文介绍了在编译时检查头文件的依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器是否提供自动检查每个源文件(及其关联的头文件,如果有的话)是否包含所有其他头文件的能力?

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

header1.h

#include <string>
...

header2.h

header2.h

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

source2.cpp

source2.cpp

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



我使用g ++和Visual Studio,所以我的问题主要适用于这些编译器。谢谢!

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

推荐答案

据我所知,没有自动的方式。

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

我的建议是将包含内容限制在头文件中仅限于.h
中定义的接口所需。在C ++编码标准(Sutter,Alexandrescu)中,您可以找到一个项目,这显然(它的标题文件使自己的头文件)。我引用:

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


不包括您不需要的标题;他们只是创建了离散依赖。
考虑这种技术来帮助实现头自助:在你的构建中,编译
每个头隔离并验证没有错误或警告。

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.

此外,您应该首先包含自己的.h,因为这样可以最大限度地发现是否存在包含错误。

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

在所有情况下,标题应该是可交换的,所以如果你的文件包括ah和bh,两个可能的顺序应该做。

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

这篇关于在编译时检查头文件的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆