In C, how come function may have several declarations but only one definition? -


in c, how come function may have several declarations 1 definition? can elaborate on please!

in order allow multiple definitions, must require definition functionally identical - otherwise must have way decide run, @ point might give them different names.

proving 2 function definitions identical non-trivial problem. since functions may declared in multiple translation units, need compare them @ link stage in order prove identical. problem when start dealing compiler optimizations may take account other contents of these translation units. example, consider:

const char *foo() {   return "world"; } 

simple enough, right? compile 2 files. a.c contains foo. b.c contains well:

const char *bar() {   return "hello world"; } 

the compiler may choose make foo()'s "world" point middle of bar()'s "hello world". linker must somehow determine 2 foo()s identical, though point non-identical constant data.

a bigger issue comes in when aliasing rules considered. consider:

void frob(int *p);  int foo() {   int x = 1;   x++;   frob(&x); } 

compiled alone, might result in assembly code similar to:

foo:     sub %esp, 4               ; allocate stack space x     mov dword [%esp], 2       ; set x 2 (x++ combined initialization)     push %esp                 ; push %x stack frob's argument     call frob     mov %eax, dword [%esp+4]  ; load value of x eax return value     add %esp, 8               ; clear stack of frob's argument , x     ret                       ; return 

now let's compile definition of frob in scope:

void frob(int *p) { /* no-op */ } 

now have:

frob:     ret                       ; return  foo:     mov %eax, 2               ; return value = 2     ret                       ; return 

how can linker tell 2 foo definitions identical?

given difficulties of proving function bodies identical, c opts forbid defining same function twice. c++ uses different approach inline , template functions; doesn't check, , assumes they're identical.

as declarations on other hand, there defined rules proving compatibility, there's no problem in allowing multiple compatible declarations.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -