Search code examples
c++headerextern

Why does it seem not OK to using "extern int a" in global scope?


main.cpp

#include <iostream>
#include "test.h"
int a = 999;
int main() {
    std::cout << a << std::endl;
    printa();

    return 0;
}

test.h

#include <iostream>
extern const int a;
void printa(void) {
    std::cout << a << std::endl;
}

When compiled and running, it works fine

But when I changed main.cpp to

#include <iostream>
#include "test.h"
extern int a = 999; //here is the change, I have added extern
int main() {
    std::cout << a << std::endl;
    printa();

    return 0;
}

Works good but a warning shows up.

warning: a initialized and declared

What is wrong? Why does it seem not OK to using "extern int a" in global scope ?


Solution

  • Why does it seem not OK to using "extern int a" in global scope ?

    Actually it is "OK". In your header, your variable is declared extern in the global scope and everything is fine with it.

    1. You don't have to repeat the extern keyword when you want to initialize the variable. The variable is already known as extern at this point (in the .cpp) since the declaration has been already performed when including the header.
    2. As @Jarod42 mentioned in comment, your const declaration and non-const initialization mismatch.
    3. If you initialize the extern variable when you declare it, then the extern becomes obsolete. The semantic of extern is "Ok, I defer the initialization somewhere else". Hence the warning.

    For instance:

    .h

    extern int a;       // declaration, as extern (will be initialized somewhere else)
    extern const int b; // example with const
    

    .cpp

    int a = 42;         // initialization
    const int b = 4422; // initialization