Under what circumstances can an extern variable be used in definition?

后端 未结 6 1225
情书的邮戳
情书的邮戳 2020-12-21 12:16

I am very very sorry. I didn\'t know my incomplete code attachment would create such a mess. I am very glad to see so many sincere helps.

This code will compile:

6条回答
  •  悲&欢浪女
    2020-12-21 13:03

    The question apparently stems from some misconception.

    Some people believe that extern keyword always turns a definition into a non-defining declaration. This is simply not true.

    The keyword extern simply gives the declared entity external linkage. It can be applied to declarations. It can be applied to definitions (and remember that definitions are declarations as well).

    So, saying that one can't define an extern entity is absolutely incorrect. One can. There's no problem with that at all.

    The confusion is usually caused by the fact that when you apply extern to a definition like

    int x; // no initializer
    

    that definition suddenly turns into a non-defining declaration. This is true, but this is is no more than a one-off quirk of extern keyword that has to be remembered. If you take a definition like

    int x = 42;
    

    then applying the extern keyword to it will still preserve it as a definition, i.e. no quirks in this case.

提交回复
热议问题