When to use extern in C++

前端 未结 4 2126
清歌不尽
清歌不尽 2020-11-22 03:15

I\'m reading \"Think in C++\" and it just introduced the extern declaration. For example:

extern int x;
extern float y;

I thi

4条回答
  •  孤城傲影
    2020-11-22 03:44

    It's all about the linkage.

    The previous answers provided good explainations about extern.

    But I want to add an important point.

    You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

    In C++, a const variable has internal linkage by default (not like C).

    So this scenario will lead to linking error:

    Source 1 :

    const int global = 255; //wrong way to make a definition of global const variable in C++
    

    Source 2 :

    extern const int global; //declaration
    

    It need to be like this:

    Source 1 :

    extern const int global = 255; //a definition of global const variable in C++
    

    Source 2 :

    extern const int global; //declaration
    

提交回复
热议问题