How to correctly use the extern keyword in C

后端 未结 10 2265
感情败类
感情败类 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:18

    extern tells the compiler that this data is defined somewhere and will be connected with the linker.

    With the help of the responses here and talking to a few friends here is the practical example of a use of extern.

    Example 1 - to show a pitfall:

    File stdio.h:
    
    int errno;
    /* other stuff...*/
    

    myCFile1.c:
    #include 
    
    Code...
    

    myCFile2.c:
    #include 
    
    Code...
    

    If myCFile1.o and myCFile2.o are linked, each of the c files have separate copies of errno. This is a problem as the same errno is supposed to be available in all linked files.

    Example 2 - The fix.

    File stdio.h:
    
    extern int errno;
    /* other stuff...*/
    

    File stdio.c
    
    int errno;
    

    myCFile1.c:
    #include 
    
    Code...
    

    myCFile2.c:
    #include 
    
    Code...
    

    Now if both myCFile1.o and MyCFile2.o are linked by the linker they will both point to the same errno. Thus, solving the implementation with extern.

提交回复
热议问题