Are unused includes harmful in C/C++?

后端 未结 10 596
说谎
说谎 2020-12-23 14:27

What are the negative consequences of unused includes?

I\'m aware they result in increased binary size (or do they?), anything else?

10条回答
  •  醉话见心
    2020-12-23 14:52

    I'll assume the headers can all be considered as "sincere", that is, are not precisely written with the aim of sabotaging your code.

    • It will usually slow the compilation (pre-compiled headers will mitigate this point)

    • it implies dependencies where none really exist (this is a semantic errors, not an actual error)

    • macros will pollute your code (mitigated by the prefixing of macros with namespace-like names, as in BOOST_FOREACH instead of FOREACH)

    • an header could imply a link to another library. in some case, an unused header could ask the linker to link your code with an external library (see MSCV's #pragma comment(lib, "")). I believe a good linker would not keep the library's reference if it's not used (IIRC, MSVC's linker will not keep the reference of an unused library).

    • a removed header is one less source of unexpected bugs. if you don't trust the header (some coders are better than others...), then removing it removes a risk (you won't like including an header changing the struct alignment of everything after it : the generated bugs are... illuminating...).

    • an header's static variable declaration will pollute your code. Each static variable declaration will result in a global variable declared in your compiled source.

    • C symbol names will pollute your code. The declarations in the header will pollute your global or struct namespace (and more probably, both, as structs are usually typedef-ed to bring their type into the global namespace). This is mitigated by libraries prefixing their symbols with some kind of "namespace name", like SDL_CreateMutex for SDL.

    • non-namespaced C++ symbol names will pollute your code. For the same reasons above. The same goes for headers making wrong use of the using namespace statement. Now, correct C++ code will namespace its symbols. Yes, this means that you should usually not trust a C++ header declaring its symbols in the global namespace...

提交回复
热议问题