Home > Back-end >  Make extern variable can't be accessed in specific files
Make extern variable can't be accessed in specific files

Time:10-18

So I have:

foo.h

#ifndef FOO_H
#define FOO_H

extern int bar;

void change_bar_value(const int& value);

#endif

foo.cpp

#include "foo.h"

int bar = 10;

void change_bar_value(const int& value)
{
    bar = value;
}

and main.cpp

#include "foo.h"

int main()
{
    bar = 20;
    change_bar_value(20);
}

So I want that you can't direcly change bar in main.cpp, but you can call a function that changes the value of bar. So how can I do it?

CodePudding user response:

"Don't make it extern" is the obvious answer, and the generally preferrable solution.

If you desparately want something is globally readable but not writeable, alias it with a const reference.
(And don't pass primitives by const reference - it is a pointless pessimization.)

foo.h:

extern const int& bar;
void change_bar_value(int value);

foo.cpp:

static int local_bar;
const int& bar = local_bar;

void change_bar_value(int value)
{
    local_bar = value;
}
  • Related