Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use `extern void my_func();` rather than including `my_utils.h`?

Tags:

c

extern

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?

like image 601
coolaj86 Avatar asked Oct 06 '10 22:10

coolaj86


People also ask

What is extern void?

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.

When should I use extern in C?

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.

Should I use extern header file?

With variables, it is important to use the extern keyword (and no initializer) in the header file.

What does extern mean in a function declaration?

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.


1 Answers

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.

like image 145
Oliver Charlesworth Avatar answered Oct 26 '22 08:10

Oliver Charlesworth