0

I wrote the following code

#include<iostream>
using namespace std;
extern int var = 0;
int main(void)
{
 var = 10;
 return 0;
}

I used

g++ -std=c++11 test.cpp -o test

and

 g++ test.cpp -o test

to compile the code. And I got the following warning

test.cpp:44:12: warning: 'extern' variable has an initializer [-Wextern-initializer]
extern int var = 0;
           ^
1 warning generated.

What does this mean? Do I need to worry about this? How can I avoid it? Thanks a lot~

2
  • 2
    When you declare a variable using extern , you are telling the compiler that the variable was defined elsewhere and the definition will be provided at the time of linking. Inclusion is a different thing altogether. Commented Jun 26, 2018 at 3:56
  • Since you've already accepted an answer, I'll just point out that extern int var = 0; is not just a declaration; it also defines the variable var, because of the initializer. In this context, the extern is essentially noise. Commented Jun 26, 2018 at 11:55

1 Answer 1

5

One explanation of external:

The extern keyword tells the compiler that a variable is declared in another source module (outside of the current scope). The linker then finds this actual declaration and sets up the extern variable to point to the correct location. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will throw an "Unresolved external symbol" error.

Since it’s declared elsewhere, that elsewhere is the place to initialize it.

More briefly, if you’re declaring it in a single-file program, that’s enough; drop the external phrase.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.