syntax - Effects of the extern keyword on C functions -


in c, did not notice effect of extern keyword used before function declaration. @ first, thought when defining extern int f(); in single file forces implement outside of file's scope. found out both:

extern int f(); int f() {return 0;} 

and

extern int f() {return 0;} 

compile fine, no warnings gcc. used gcc -wall -ansi; wouldn't accept // comments.

are there effects using extern before function definitions? or optional keyword no side effects functions.

in latter case don't understand why did standard designers chose litter grammar superfluous keywords.

edit: clarify, know there's usage extern in variables, i'm asking extern in functions.

we have 2 files, foo.c , bar.c.

here foo.c

#include <stdio.h>  volatile unsigned int stop_now = 0; extern void bar_function(void);  int main(void) {   while (1) {      bar_function();      stop_now = 1;   }   return 0; } 

now, here bar.c

#include <stdio.h>  extern volatile unsigned int stop_now;  void bar_function(void) {    while (! stop_now) {       printf("hello, world!\n");       sleep(30);    } } 

as can see, have no shared header between foo.c , bar.c , bar.c needs declared in foo.c when it's linked, , foo.c needs function bar.c when it's linked.

by using 'extern', telling compiler whatever follows found (non-static) @ link time, don't reserve since encountered later.

it's useful if need share global between modules , don't want put / initialize in header.

technically, every function in library public header 'extern', labeling them such has little no benefit, depending on compiler. compilers can figure out on own. see, functions defined somewhere else.

in above example, main() print hello world once, continue enter bar_function(). note, bar_function() not going return in example (since it's simple example). imagine stop_now being modified when signal serviced (hence, volatile) if doesn't seem practical enough.

externs useful things signal handlers, mutex don't want put in header or structure, etc. compilers optimize ensure don't reserve memory external objects, since know they'll reserving in module object defined. however, again, there's little point in specifying modern compilers when prototyping public functions.

hope helps :)


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -