0

I'm having a hard time understanding externs, and I've read multiple solutions but I still don't understand the concept behind them. In a header file that gets included multiple times, having a variable will cause an error due to the fact that the variable has been declared more than once. Therefore int x in a .h file is not allowed. However, extern int x is allowed. I've read that it is because it is not defined yet, only declared. So if I were to declare it inside a function, wouldn't x be a local variable to the function instead of a global scope variable?

extern int x = 1 provides an error, I'm assuming because it is defining the variable. However, static int x = 1 does not give an error, since static will not declare a 2nd time in the same scope. This begs the question, if static and extern both provide the same outcome, which is a shared global variable, declared once, and can be modified by any, then what is the difference between a static and an extern variable? I know the conceptual difference, which is static defines it only once, but externs awaits until it gets defined in another .cpp file, but behavioral wise, aren't they used in the same manner? Or is the extern local to the file that included it only?

Also, if an extern is to be defined later on, doesn't that make having an extern useless? What would be the benefit of an extern if it can't be used?

thethiny
  • 1,125
  • 1
  • 10
  • 26
  • https://en.cppreference.com/w/cpp/language/storage_duration – bolov Jan 08 '21 at 02:11
  • there are more question on SO about extern and static, but I can only set 5 duplicates. Go forth and read. All of your questions are answered. Read carefully the link in my previous comment. You have some misconceptions. These links will clarify them. – bolov Jan 08 '21 at 02:18
  • @bolov Alright, thanks for the help, I will surely do read. – thethiny Jan 08 '21 at 02:21

0 Answers0