Home > Net >  Why are you allowed to re-define a extern variable in c ?
Why are you allowed to re-define a extern variable in c ?

Time:11-29

I have an extern variable declared in driver.h:

namespace org::lib {
   extern bool myVar;
   void myFunction();
}

I also have it defined in driver.cpp:

#include driver.h
namespace org::lib {
       bool myVar = false;
       void myFunction(){
          if (myVar){
            //....
          }
       }
}

Now I have main.cpp which redefines myVar:

 #include driver.h
  using org;

  int main(int arc, char** argv){
       lib::myVar = true; //redefines it to be true, while it was defined as false in driver.cpp
       lib::myFunction();    
  }

Why doesn't compiling main.cpp give me a redefinition error on myVar ? Isn't it defined already in driver.cpp, and redefined again in main.cpp ?

Ah never mind, you are re-assigning it in main.cpp.

CodePudding user response:

You don't define the variable in main, you assign it a new value

  •  Tags:  
  • c
  • Related