3

In Visual Studio (C++), is there a way to easily find duplicate headers that are defined in .cpp files?

I'm also trying to find ways to detect this situation:

  • A includes B includes C
  • A includes C
  • => A doesn't need to include C
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • Why do you need to detect this? If your headers have proper include guards, it shouldn't matter. If you're trying to speed up your compile times, I assure you this is not the bottleneck, and removing these is not going to speed up your compile times noticeably. – Adam Rosenfield Jan 04 '09 at 15:46
  • Code cleanup, I'm looking at one .cpp file that has over 50 includes. – Brian R. Bondy Jan 04 '09 at 15:49
  • Actually, if A.cpp needs class B and class C, it should include B.h and C.h - even if B.h includes C.h The reason is that a maintenance programmer may remove C.h from B.h, if he can apply the pimp idiom. This is a valid change and should not break A.cpp – MSalters Jan 05 '09 at 09:40
  • Couldn't the person applying the pimp idiom just add the include in that case? – Brian R. Bondy Jan 07 '09 at 13:08

3 Answers3

5

If you want to detect this situation you could add this macro to the top of every file. Substitute A for the name of the file

#if A_H
#error "Duplicate include"
#else
#define A_H
#endif
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • That's a clever solution. I haven't seen that technique before. I would suggest using #warning though, since eliminating ALL duplicate includes can result in scenarios that a far uglier than the problem this solves. – Drew Dormann Jan 04 '09 at 17:47
4

Generally, you mark them with #pragma once, or the equivalent macro guard and stop caring about it.

If you're using MS compiler, you can put a #pragma message (IIRC, it might be a #pragma warning or #pragma error instead) with the name of the header file at the very top of each header file and your build output will show the list of every one that's being included per file that's compiled.

That would work best for your header files, as the system ones will not be included.

If you want to see all included headers, edit the compile options to include /P (preprocess to a file) that will not compile your code, but instead will redirect the pre-processer to a file, you can then grep through it to see the #include statements. Be aware these files will be large.

gbjbaanb
  • 51,617
  • 12
  • 104
  • 148
0

PC-Lint (and probably other lint tools) can indicate unused include files.

Steve Fallows
  • 6,274
  • 5
  • 47
  • 67