简体   繁体   中英

Does C++ compiler optimize out #includes that are not used?

When building a growing library of classes/functions, I've commonly seen a sort of "umbrella" header file that #includes all the common header files of a project. For example:

dsp.h
#include "file1.h"
#include "file2.h"
...
#include "filex.h"

Sometimes I might need everything, but other times maybe only a selection of features/options. If #include dsp.h, but don't use anything from file2.h for example, does the compiler know? Is it possible for it to optimize it out in the build?

Otherwise, my solution is to wrap optional code inside preprocessor directives and then define what I need. Perhaps this is a safer, more efficient solution?

Are you talking about code optimization or optimization of build time?

Unnecessary, unused headers will not change the code that is being generated, so there is no question of optimization here.

However, it will increase build time. This is not optimized by build tools. If you are looking to optimize build time, look at the book Large Scale C++ Software Design by John Lakos .

The preprocessor doesn't do any optimization. It doesn't know anything about the semantics of your code and thus cannot tell whether you're using anything from a header file or not. So no, #include statements are not optimized out.

Since the preprocessor is a separate program (and language) from the C++ compiler, there's no way for the preprocessor to know what is used. So the compiler will receive everything that was in the header file.

The include files are are read, and are inserted part of the source code before the compiler really starts generating code.

Yes. As a general rule, things that are not referenced by the program are not put into the final executable. It is ok to think of that as being an optimization. The details will differ depending on the compiler and linker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM