简体   繁体   English

C ++中的静态变量声明和定义

[英]static variable declaration and definition in C++

I have a sample code as shown below: 我有一个示例代码,如下所示:

 class myclass
{
public:
    static int j;
    myclass(){};
    ~myclass(){};
};

int main(int argc, char** argv) {
    myclass obj;
    return EXIT_SUCCESS;
}

Now I have declared a static int inside myclass and although I have not defined it, the compiler does not give me any errors until I began using the static variable. 现在,我在myclass中声明了一个static int,尽管我还没有定义它,但是直到我开始使用static变量时,编译器才会给我任何错误。 Why is that? 这是为什么?

Because these are linker errors, not compiler errors. 因为这些是链接器错误,而不是编译器错误。 Linker errors never arise until you use an undefined symbol. 除非使用未定义的符号,否则永远不会出现链接器错误。

"the compiler does not give me any errors until I began using the static variable. Why is that?" “在开始使用静态变量之前,编译器不会给我任何错误。这是为什么?”

Because it didn't need to be linked with your code until that point (when you start to use it). 因为直到那时(开始使用它)才需要将其与您的代码链接。 Unused code is ignored / stripped off by the linker. 链接器将忽略/删除未使用的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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