Why would you use `extern void my_func();` rather than including `my_utils.h`?
21,398
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.
Author by
coolaj86
<3 Go, Rust, Node, VanillaJS ✓ Python, C ✗ Java, C++ </3 PHP (and therefore React) #FathersMatter #BlackFathersMatter
Updated on September 14, 2020Comments
-
coolaj86 over 3 years
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? -
Donotalo over 13 yearsfunctions are always extern by default in C? are you sure??
-
Oliver Charlesworth over 13 years@Donotalo: Pretty sure, but it is midnight, so who knows what tiredness has done to my brain.
-
Donotalo over 13 yearsi'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. -
Oliver Charlesworth over 13 years@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 explicitextern
functions! -
Donotalo over 13 yearsno we don't put
extern
functions in header. we have to put it in .c files where they are called. -
Donotalo over 13 yearsi 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. -
Oliver Charlesworth over 13 yearsAs discussed in the comments to my answer, use of
extern
is unnecessary. -
Donotalo over 13 years@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 calledcout << fun() << endl;
compiler says fun() is undeclared. then i wroteextern int fun();
before main(). then it worked. -
0xbadf00d almost 10 years@Donotalo A function declaration
R func(T arg)
tells the compiler that there is a function calledfunc
which returns a value of typeR
and has a formal parameter of typeT
calledarg
. This allows the use of the function name in the context of the declaration. The linker is responsible for resolving such a name and find the corresponding function definition which might can be found in a different compilation unit.