Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External linkage in C

Tags:

c

K&R says:

by default external variables and functions have the property that all references to them by the same name, even from functions compiled separately, are references to same thing

Please explain what this means, I don't understand it

like image 859
ashna Avatar asked Jun 22 '10 13:06

ashna


1 Answers

Consider two functions:

extern int extern_sqr(int i) { return i * i; }
static int static_dbl(int i) { return i * 2; }

Then people who refer to extern_sqr will be referring to that function. This is opposed to static linkage, where only people from within the "translation unit" (roughly the file it's defined) can access the function static_dbl.

It turns out, that the extern is implied by default in c. So, you would get the same behavior, if you wrote:

int extern_sqr(int i) { return i * i; }

Newer C standards still require a "function declaration" so, usually in a header file somewhere, you'll encounter:

int extern_sqr(int i);  // Note: 'i' is optional

Which says "somewhere, in some other translation unit, I have a function called extern_sqr.

The same logic applies to variables.

like image 116
Stephen Avatar answered Sep 22 '22 01:09

Stephen