Search code examples
cstructextern

Using extern for structures in C


Why we cannot use extern to make struct accessible in more than one .c file?

I know that advice is to put a definition of struct in .h file and to include that .h file to every .c file we use that struct, but why we can use `extern for variables but it does not work with structs?

To extern variable:

  1. Define variable in .c file
  2. extern variable in .c file where we want it to be used
  3. build both .c files, the one where variable is defined and the one where it is used

But what is the case with structures?

Correct me if I am wrong somewhere.


Solution

  • The storage-class specifier extern is used to control linkage (see C11 draft 6.2.2), i.e. which identifiers refer to the same object or function.

    A struct however, is not a definition (i.e. storage reservation for an object or function body for a function, see 6.7.5), but a type declaration (see 6.2.5.20 and 6.7.2.1.6).


    Remark: This distinction is also made explicit in 6.2.2.6:

    The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; ...