Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is commenting out a #include a safe way to see if it's unneeded?

Tags:

c

I like to keep my files clean, so I prefer to take out includes I don't need. Lately I've been just commenting the includes out and seeing if it compiles without warnings (-Wall -Wextra -pedantic, minus a couple very specific ones). I figure if it compiles without warnings I didn't need it.

Is this actually a safe way to check if an include is needed or can it introduce UB or other problems? Are there any specific warnings I need to be sure are enabled to catch potential problems?

n.b. I'm actually using Objective C and clang, so anything specific to those is appreciated, but given the flexibility of Objective C I think if there's any trouble it will be a general C thing. Certainly any problems in C will affect Objective C.

like image 251
Kevin Avatar asked Mar 24 '14 18:03

Kevin


3 Answers

In principle, yes.

The exception would be if two headers interact in some hidden way. Say, if you:

  • include two different headers which define the same symbol differently,
  • both definitions are syntactically valid and well-typed,
  • but one definition is good, the other breaks your program at run-time.

Hopefully, your header files are not structured like that. It's somewhat unlikely, though not inconceivable.

I'd be more comfortable doing this if I had good (unit) tests.

like image 133
Søren Debois Avatar answered Oct 02 '22 12:10

Søren Debois


Usually just commenting out the inclusion of the header is safe, meaning: if the header is needed then there will be compiler errors when you remove it, and (usually) if the header is not needed, the code will still compile fine.

This should not be done without inspecting the header to see what it adds though, as there is the (not exactly typical) possibility that a header only provides optional #define's (or #undef's) which will alter, but not break, the way a program is compiled.

The only way to be sure is to build your code without the header (if it's able to build in the first place) and run a proper regimen of testing to ensure its behavior has not changed.

like image 36
mah Avatar answered Oct 02 '22 12:10

mah


No. Apart from the reasons already mentioned in other answers, it's possible that the header is needed and another header includes it indirectly. If you remove the #include, you won't see an error but there may be errors on other platforms.

like image 23
nwellnhof Avatar answered Oct 02 '22 14:10

nwellnhof