How should I detect unnecessary #include files in

2019-01-03 01:46发布

I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp file. Are there any good tools for detecting both of these cases?

20条回答
Bombasti
2楼-- · 2019-01-03 01:47

While it won't reveal unneeded include files, Visual studio has a setting /showIncludes (right click on a .cpp file, Properties->C/C++->Advanced) that will output a tree of all included files at compile time. This can help in identifying files that shouldn't need to be included.

You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.

查看更多
地球回转人心会变
3楼-- · 2019-01-03 01:47

If you would work with Eclipse CDT you could try out http://includator.com to optimize your include structure. However, Includator might not know enough about VC++'s predefined includes and setting up CDT to use VC++ with correct includes is not built into CDT yet.

查看更多
不美不萌又怎样
4楼-- · 2019-01-03 01:48

Adding one or both of the following #defines will exclude often unnecessary header files and may substantially improve compile times especially if the code that is not using Windows API functions.

#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN

See http://support.microsoft.com/kb/166474

查看更多
Viruses.
5楼-- · 2019-01-03 01:49

If your header files generally start with

#ifndef __SOMEHEADER_H__
#define __SOMEHEADER_H__
// header contents
#endif

(as opposed to using #pragma once) you could change that to:

#ifndef __SOMEHEADER_H__
#define __SOMEHEADER_H__
// header contents
#else 
#pragma message("Someheader.h superfluously included")
#endif

And since the compiler outputs the name of the cpp file being compiled, that would let you know at least which cpp file is causing the header to be brought in multiple times.

查看更多
一夜七次
6楼-- · 2019-01-03 01:50

The latest Jetbrains IDE, CLion, automatically shows (in gray) the includes that are not used in the current file.

It is also possible to have the list of all the unused includes (and also functions, methods, etc...) from the IDE.

查看更多
再贱就再见
7楼-- · 2019-01-03 01:55

There's a new Clang-based tool, include-what-you-use, that aims to do this.

查看更多
登录 后发表回答