user69514
user69514

Reputation: 27629

C++ header files simple question

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"

Upvotes: 0

Views: 1407

Answers (4)

quark
quark

Reputation: 15852

Not directly. However if the .cc or .c file #includes a file, then any headers #included 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 #included 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?

Upvotes: 2

Simon Parker
Simon Parker

Reputation: 1834

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.

Upvotes: 0

William Bell
William Bell

Reputation: 553

No, neither in C or C++. It often happens that headers are included indirectly which is what may have occurred in your prior experience.

Upvotes: 0

rlbond
rlbond

Reputation: 67739

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.

Upvotes: 0

Related Questions