I'm working on some code I didn't write and noticed that there are many extern void my_func();
.
My understanding is that extern
in for global variables, not for functions.
Is there a practical reason to declare a function as extern
rather than putting it in a header file and including that? Or is this just a stylistic choice?
extern void f(); declares that there is a function f taking no arguments and with no return value defined somewhere in the program; extern is redundant, but sometimes considered good style.
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
With variables, it is important to use the extern keyword (and no initializer) in the header file.
In a non- const global variable declaration, extern specifies that the variable or function is defined in another translation unit. The extern must be applied in all files except the one where the variable is defined. In a const variable declaration, it specifies that the variable has external linkage.
This is only needed if, for some reason, the header file doesn't declare the function. And extern
is always unnecessary for functions, as functions are always extern
by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With