+ 2
extern vs global
Hi global is not something we should choose for a variable. Is it correct for extern as well? If so, does it make sense to never use it at all or there is some case which forces us to use the extern variables.
6 Answers
+ 2
An example of using extern would be a header file which has a namespace and a variable within the namespace. You have to declare it as extern if you want to initialize it in a source file and not in the namespace.
In my line of work, where I use not only compile-time C++ but also an interpreter that compiles at run-time (just in time compilation) if I want to have a variable outside the interpreter to be available inside the interpreter I have no choice but to declare it as extern.
I personally am not crazy about slapping on extern, but sometimes it is really the only way to go about things.
+ 3
Ketan,
Extern can be essential and the idea of never using it is nonsense. Also certain applications/programs you create might need a global variable - itâs perfectly fine to use a global (just only when a global is really needed)
Iâll give you a simple example, multiple compilation - if you want to use the same variable across multiple files, you must declare the variable as external (extern). This tells the compiler that the variables definition is external, in a different file.
Thereâs a lot more to this though, with extern templates and instantiation.
+ 1
Ketan,
The main point is that you are avoiding redefinition.
The compiler needs to know how to use the object (var type). The extern is a promise that the definition exists somewhere, doesnât matter where.
Itâs then the linkers job to resolve any references to the one definition. External linkage.
Without using the extern modifier the compiler would look for the definition within the single unit.
0
Thanks DavX
I got your point and I am in line with what you are trying to say. But if i go in more details, why one would like to go with same variable name in multiple files? Isnt it a bad design ?
0
Hello Ketan,
No not at all, depending on the size of the project its crucial to break it down into smaller bitsized chunks.
Itâs a good practice to write classes in seperate files - easier to manage and test.
Plus depending on how you go about it, you can get away with re-compiling just one file when making changes. Reducing compile time etc.
Using extern you can avoid redefinition of a variable thatâs common for both/all files.
If your just learning I wouldnât get too caught up on this. Just knowing the concept is enough, when you get to the point of needing to use you will understand why its an important feature.
0
I am not saying modularization i.e. seperate files as bad practice.
What I am saying bad practice is a need of extern variable or same name. Why one need it and cant we give ownership to a single class or file rather than more files ?