1

How can I make visible variables/functions in particular files? For example, lets say I have this hierachy of files:

a.h

extern int var; 

a.cpp

#include "a.h" int var; 

b.h

#include "a.h" void function(); 

b.cpp

#include "b.h" void function() { var = 0; } 

in main.cpp I want to be able call function(), but not to access var variable

#include "b.h" int main(int argc, char** argv) { function(); /* possible to call */ var = 0 /* var shouldn't be visible */ } 

I don't want file a.h to be included in main.cpp - only b.h. How can I achieve this?

1
  • 2
    Don't include a.h in b.h but include it in b.cpp Commented Jul 26, 2012 at 15:53

2 Answers 2

6

a.h doesn't need to be included in b.h, only b.cpp. This is because var is only needed by the function definition, not its declaration. This goes along with the rule not to include headers in other headers unless you absolutely have to.

b.h

void function(); 

b.cpp

#include "b.h" #include "a.h" void function() { var = 0; } 
Sign up to request clarification or add additional context in comments.

Comments

3

I think you need to stop trying to hide information using the visibility of files, and start looking in to C++ classes which allow you to "hide" things that "methods" use by way of private members:

class A { private: int var; public: void function() { var = 0; }; }; 

2 Comments

Agree, hiding declarations have weaker privacy guarantees than private members, although both can be cheated if the programmer really wants to.
@lvella, absolutely agree - but you have to really set out to circumvent a class, whereas accidentally including the wrong file will bring a whole heap of hurt. Especially as these are globals, without even namespaces to cuddle them by the warm fire with.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.