External linkage in C

前端 未结 2 1264
感动是毒
感动是毒 2021-01-13 10:31

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

相关标签:
2条回答
  • 2021-01-13 11:19

    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.

    0 讨论(0)
  • 2021-01-13 11:21

    external variables and functions are global, i.e. hold the same values (for variables) or definitions (for functions) even when called from different *.c files within your program.

    0 讨论(0)
提交回复
热议问题