1

Is there a way to compile source code with g++, and have the compiler warn me if I have not included a file in another file where I should have?

For example, in a large project it is often quite easy to write some code in fileA, which uses another function from fileC (which contains the function declaration), but forget to add the include statement. Such an error can be hidden if fileA also includes another file, fileB, where fileB includes fileC.

This will then compile without error, however if the code is modified at a later date, and we remove the #include fileB.hpp from fileA, then compilation will fail, because we originally forgot to include fileC many months ago!

Is there a compiler switch which will warn us about this problem? Similarly, is there the reverse switch, which will warn us when we #include something which is unnecessary?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

2 Answers2

3

Not exactly answering the question, but using forward declarations and keeping includes in headers minimal might help in avoiding such problems.

If you only use forward declarations in your hpp files, they would be independent from each other, and you will be forced to include specific .hpp files into each .cpp unit being compiled.

Ilya Kobelevskiy
  • 5,245
  • 4
  • 24
  • 41
2

I don't believe there's such an option because practically speaking it would be really hard to implement. How is the compiler supposed to know which header file is not included (consider a case where you have a free template function in one header and a specialization in another).

But have no fear, in practice this isn't a big deal. If you never remove the include for fileB your code will continue to compile just fine, and if you do remove it you'll get a handy error right away, telling you exactly which identifier is missing, enabling you to go include the proper header yourself at that time!

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • +1'd but I wouldn't say its not a big deal at all :-) particularly when you suddenly find yourself in a circular dependency that you don't even realize why you are in in the first place. Plus it's never fun when I change an include in my own header perhaps because it was unused and I find I break a dozen other files and unit tests because they were abusing my includes too. – UpAndAdam Sep 04 '13 at 19:50