简体   繁体   中英

Hiding visibility of variables in a c++ source file

I am using cpp file to initialize some data

// foo.cpp

#include "foo.h"

int val = 5;

& using header to share it with other files in the project.

// foo.h

extern int val;

inline int get() {
    return val;
}

But I don't want the variable val to be accessible in other files of the project. I want to access the value through get() function. Is there any way to achieve this?

I've tried another approach...

// foo.h

class foo {

private:

    static int val;

public:

    static int get() {
        return val;
    }

    static void set();
}

&...

// foo.cpp

void foo::set() {
    val = 5;
}

but it too doesn't work. Getting linker error: unresolved external symbol "private: static int foo::val" .

在foo.cpp中添加:-

 int foo::val;

Put in the .cpp file

int foo:val = 5;

to give it the space it requires.

You need class member or free variable? If you want free variable, just remove variable declaration from header file, remove definition of get() (leave the declaration) and implement get() in .cpp file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM