Is extern keyword for function necessary at all in C?

前端 未结 4 1228
滥情空心
滥情空心 2020-12-05 11:25

It appears to me that even if I refer to a function in another file with out extern declaration, gcc can still compile that unit. So I am wondering whether the extern declar

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 11:47

    You do not necessarily "need" extern for variables.

    When C was invented Unix linkers were also written, and they advanced the art in unheralded but clever ways. One contribution was defining all symbols as small "common blocks". This allowed a single syntax for declarations with no required specification of which module was allocating the space. (Only one module could actually initialize the object, but no one was required to.)

    There are really three considerations.

    1. Forward declarations for prototypes. (Optional, because legacy C has to compile without them.)

    2. Extern declarations for non-function objects (variables) in all files except one. (Needed only on non-Unix systems that also have crummy linkers. Hopefully this is rare these days.)

    3. For functions, extern is already the assumption if no function body is present to form a definition.

提交回复
热议问题