Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern function during linkage?

Tags:

c

linux

I have this weird thing:

in a file1.c there's

extern void foo(int x, int y);
..
..

int tmp = foo(1,2);

in the project I could find only this foo():

in file2.c :

int foo(int x, int y, int z)
{
....
}

in file2.h :

int foo(int x, int y, int z);

file2.h isn't included in file1.c (this is why who wrote it used extern, i guess).

this project compiles fine, I think that's because in file1.c foo() will be looked for only during linkage, am I right?

but my real question is : why is the linkage succssful ? after all, there is no such function as foo with 2 parameters.... and i'm in c .. so there's no overloading..

so what's going on ?

like image 446
user1047069 Avatar asked Nov 26 '14 08:11

user1047069


1 Answers

Because there is no overloading, the C compiler does not decorate the function names. The linker finds in file2.c a reference to function foo and in file1.c it finds a function foo. It cannot know their parameter lists do not match and happily use them.

Of course, when the function foo runs the value of z is garbage and the behavior of the program becomes unpredictable from that point on.

like image 122
axiac Avatar answered Sep 28 '22 15:09

axiac