Let's say I have a header file called inclusions.h
that has all the #include <...>
s for my project. inclusions.h
includes another header file called settings.h
, where vario开发者_C百科us constants can be modified.
If #include <math.h>
in inclusions.h
, will settings.h
have access to the math library as well? Or do I have to #include <math.h>
in settings.h
as well?
If math.h is included before settings.h, settings.h should also have access to math.h. But to ensure the access (and to indicate the dependencies), you should include the files where they are needed, so also in math.h.
It depends on the order of the inclusions. #include
is a preprocessor directive that simply works by textual substitution. So, if in inclusions.h
you have:
#include <math.h>
#include <settings.h>
settings "can see" math. If you have:
#include <settings.h>
#include <math.h>
it can't. But: what would happen if you used settings.h
elsewhere without including math.h
before? So in the end, try to make each include file independent.
In this case, as others have noted, depending on the order of inclusion it could be accessible. This is because those source files are a part of one translation unit (source + includes essentially) so if <math.h>
comes before "settings.h"
, it could be viewable by it. However, if settings became a part of another translation unit, or if you decided to move certain includes around that could change. To be "safe", you should just included whatever header files which are necessary for a file to have in that file.
精彩评论