Search code examples
c++staticextern

static variable followed by extern in the same file


The following piece of code compiles as well as executes fine. What exactly does the extern int a statement mean after static int a. Note that If i write static int a after extern int a, the compiler throws error as tests.cpp:6: error: a was declared extern and later static

#include<iostream>
//#include "testh.h"
using namespace std;

static int a;
extern int a;
int main()
{
        int a;
        a=3;
        cout<<a<<endl;
        cout<<::a<<endl;
        return 0;
}

Solution

  • You can declare a variable static then extern, but not extern then static. The result is that the global a still has internal linkage. There is a very similar example (using b as the variable name) in the language standard doc, section [dcl.stc], that states this.