tags:

views:

70

answers:

2

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?

+3  A: 

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.

Oli Charlesworth
functions are always extern by default in C? are you sure??
Donotalo
@Donotalo: Pretty sure, but it is midnight, so who knows what tiredness has done to my brain.
Oli Charlesworth
i'm working for micro controller for 2 years. the compiler i use is C. though not completely ANSI C, and many features of C99 are absent, but to call a non-static function defined in another file we need to `extern` its prototype, or include the header.
Donotalo
@Donotalo: Then your compiler is broken. `#include`-ing a header file with function prototypes is equivalent to writing the prototypes directly into your source file, and you don't see header files full of explicit `extern` functions!
Oli Charlesworth
no we don't put `extern` functions in header. we have to put it in .c files where they are called.
Donotalo
i got it what do you mean by: functions are always extern by default. at first i thought functions can be called across implementation files without including header and without `extern`ing it. i was wrong.
Donotalo
A: 

One use of extern functions is that suppose you have two modules: module_a (implemented in module_a.h and module_a.c files), module_b (implemented in module_b.h and module_b.c files). Now you want a specific function of module_b to use in module_a. But you don't want to expose all the functionality of module_b into module_a. So that case instead of #include "module_b.h" you can extern the required function prototype only.

Donotalo
As discussed in the comments to my answer, use of `extern` is unnecessary.
Oli Charlesworth
@Oli: I've just tested this feature using VS2008. It didn't work except `extern`. Any idea why? I have 3 files: main.cpp (contains main()), functions.h and functions.cpp. functions.cpp defines a function (named fun()) that just returns 0. from main(), i called `cout << fun() << endl;` compiler says fun() is undeclared. then i wrote `extern int fun();` before main(). then it worked.
Donotalo
@Donotalo: It will also work with simply `int fun();`.
Oli Charlesworth