Static variables in C and C++

前端 未结 5 1222
天涯浪人
天涯浪人 2021-02-07 08:33

Is there any difference between a variable declared as static outside any function between C and C++. I read that static means file scope and the varia

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 08:45

    Not really a direct answer to your question, but something closely related to watch out for if you use both C and C++.

    In C++, unlike C, global variables which are declared "const" are implicitly local to the translation unit, AS IF "static" had been used.

    Example:

    // file A
    extern const int glob;
    
    // file B
    const int glob = 42;
    

    This will work if you are using a C compiler but not with a C++ compiler. In C++, the glob variable in file B cannot be used from file A and the linker will generate an "unresolved reference" error.

提交回复
热议问题