Can .h files see what's in each other without being included? I know when I programmed in C before I could use variables in a .h file from other .h files without #include "myfile开发者_开发技巧.h". I'm trying to do the same in C++ and I keep getting "definition out of scope error"
Not directly. However if the .cc
or .c
file #include
s a file, then any headers #include
d after it will see the contents of that header. The reason is that #include
behaves like a copy-and-paste: each files contents are effectively dumped together into one big file, and the compiler only sees the combined result. For example if you have:
foo.cc:
#include <a.h>
#include <b.h>
#include <c.h>
// foo.cc's contents
Even though b.h
doesn't #include a.h
, its definitions will still be visible in b.h, because the compiler is seeing the contents of all the headers as if they were part of foo.cc
. This can be fairly problematic in practice as programs depend on definitions they aren't explicitly including. When someone changes a.h
you can start seeing errors in b.h
(or at any header #include
d afterwards).
But I don't think this completely answers your question, because this process alone shouldn't result in any "definition out of scope" errors. Care to post a code sample that has the problem?
Variables in a .h file are a precarious situation, because when you #include
a header file it's just pasted into your source file. So if you have int j;
in a header file and include it from other source files, you've basically just defined several different variables called j
, which is, of course, an error.
No, neither in C or C++. It often happens that headers are included indirectly which is what may have occurred in your prior experience.
In both C and C++ nothing is visible unless it is loaded into the compiled unit (the .c or .cpp file normally), or if it is explicitly declared.
You can forward declare a variable with "extern"
extern int somewhere_else; // now the somewhere_else defined elsewhere can be seen here
Older C compilers may have been more lenient on the need for forward declaring.
精彩评论