1
votes

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?

2
Don't include a.h in b.h but include it in b.cpp - Dave Rager

2 Answers

6
votes

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;
}
3
votes

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;
    };
};