Is using the 'extern' keyword often bad?

I was finding myself using the extern keyword quite a lot these days (mainly from laziness). I expect it to increase the compile time since it's more work for the linker, but it's there any major drawback if you use extern regularly?
If you're using extern for variables a lot, that means you're creating a lot of global variables. That's the real problem, I'd say.

If you're using it for functions, then it doesn't matter. These two declarations are equivalent:
 
void f();
 
extern void f();
Last edited on
> I expect it to increase the compile time since it's more work for the linker,
> but it's there any major drawback if you use extern regularly?

As a linkage specifier for objects with static or thread storage duration:

Usually a good idea if there must be only once instance of a (typically large) const object which is not at the global namespace scope. namespace X { extern const some_type some_object ; }

Usually a good idea if the same instance of a non-const object (again, not at the global namespace scope) which must be accessed from multiple translation units.
The classic example would be the standard stream objects. namesapace std { extern std::ostream cout; }

In both these cases, we would need to provide some mechanism to ensure that the objects are initialised before they can be accessed from other translation units (for instance with the Schwarz counter idiom); so there is a trade-off between ease of use vs ease-of-implementation.
If ease-of-implementation prevails over ease-of-use, a disguised version of a global object at namespace scope is the alternative: namespace Y { some_type& instance_of_some_type() ; }


As a language linkage specification:

Useful only if we want to write code that needs to inter-operate with other programming languages or where the C++ standard specifies that "C" linkage is required (for instance a signal handler) eg.
extern "C"
{
/* declarations of standard-layout types, functions and objects accessible by components written in C */
}



As an explicit template instantiation declaration:

Useful (in large code bases) to minimise compilation time and object file sizes, when there is a guarantee that there would be an explicit instantiation definition in some component which is a part of the program.

eg. header used by many components:
extern template X::some_class<double> ; // explicit instantiation declaration

associated implementation file:
template X::some_class<double> ; // explicit instantiation definition
Last edited on
Thank you for your answers, I just have some global control variables that I use for several dialogs and I need to juggle them between several dialogs, maybe not the best option, but they will do it for now.
Topic archived. No new replies allowed.