peto1234
peto1234

Reputation: 369

C++ variables scope in multiple files

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?

Upvotes: 1

Views: 245

Answers (2)

Moo-Juice
Moo-Juice

Reputation: 38820

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

Upvotes: 3

bames53
bames53

Reputation: 88225

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

Upvotes: 6

Related Questions