How to correctly use the extern keyword in C

后端 未结 10 2342
感情败类
感情败类 2020-11-22 08:11

My question is about when a function should be referenced with the extern keyword in C.

I am failing to see when this should be used in practice. As I

10条回答
  •  滥情空心
    2020-11-22 08:33

    All declarations of functions and variables in header files should be extern.

    Exceptions to this rule are inline functions defined in the header and variables which - although defined in the header - will have to be local to the translation unit (the source file the header gets included into): these should be static.

    In source files, extern shouldn't be used for functions and variables defined in the file. Just prefix local definitions with static and do nothing for shared definitions - they'll be external symbols by default.

    The only reason to use extern at all in a source file is to declare functions and variables which are defined in other source files and for which no header file is provided.


    Declaring function prototypes extern is actually unnecessary. Some people dislike it because it will just waste space and function declarations already have a tendency to overflow line limits. Others like it because this way, functions and variables can be treated the same way.

提交回复
热议问题