简体   繁体   中英

Manipulating a global static variable

Suppose I have main.cpp , file.h and file.cpp . Where file.cpp implements all the prototypes in file.h and main.cpp includes file.h .

Very simple structure. I was wondering If i declared a static global variable in main.cpp would it be possible to access to such variable when implementing all the functions in file.cpp ? With a quick attempt this doesn't seem to be case... I can't even compile it.

But would it be possible to work this around?

Just to clarify I have

file.h:

#ifndef __FILE_H
#define __FILE_H
#include <iostream>

void my_func();

#endif

file.cpp

#include "file.h"

using namespace std;

void my_func() {
    //do something with my_static_var
}

and main.cpp

#include "file.h"

static int my_var = 0;

int main(int argc, char** argv) {
    my_func();
    return 0;
}

Assume no classes involved

A variable with internal linkage can be referred to only from scopes within its translation unit (which typically means its source file). A variable declared with the static keyword has internal linkage.

A variable with external linkage can be referred to from other translation units (other source files). A variable has external linkage if it is not in an anonymous namespace and:

  • it is declared with the extern keyword, or
  • it is namescape-scope (such as my_var in the question) and is declared with neither const nor static (unlike my_var in the question).

Reference: storage duration

No. The static here literally means "don't let me do" what you're trying to do. It makes the object private to that translation unit, with internal linkage .

Remove the static and you'll be golden (use an extern declaration elsewhere to bring it into scope), though you should consider avoiding globals.

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