Search code examples
cstructuredefinitioninternallinkage

Why do structure definitions have internal linkage?


(I am talking about C, but it also applies to class templates in C++)

In header file, it is a custom to put all the DECLARATIONS, not definitions. However, we usually put structure definitions or class templates in header file as well without actually knowing why we can. This doesn't really make sense because they are definitions as well -- ONE DEFINITION RULE. (Yes, structure definitions and class templates don't cause any storage to set, but you still get "redefinition" error below which implies that they are definitions).

EX) defining multiple structures with same tag within same file give you a redefinition error, but defining multiple structures with same tag in multiple source files don't cause any error (same thing happens with class).

The only thing that makes sense is that structure definitions and class templates have internal linkage (opposed to default external linkage), but I can't find any references about it in K&R or reference manual. In fact, structures are not even mentioned in linkage.

I want to know the exact reference where ANSI standard points out this pheonomenon. (IMO, this is a pretty ambiguous thing which HAS TO be mentioned in ANSI standard somewhere).


EDIT I am NOT asking why structure definitions can be put into the header file.

I am asking why putting structure definition in header file won't cause redefinition error like it does when we put variable definitions in header file (and include it in multiple source files)

EX) test1.c: int a = 3; test2.c: int a = 4; Causes compile error because of redefinition. However,

test1.c: struct test { int a }; test2.c: struct test { int b }; Does not cause compile error, and the only reason I can come up with is that structure definitions either have internal linkage, or no linkage at all.


Solution

  • In C only objects and functions have linkage. Since struct in C may not contain functions or "static" member objects as in C++ your question makes not much sense, here.

    Member functions in C++ as long as they are not defined but only declared inside the struct pose no problem. If they are also defined, they are inline. The concept of inline was just invented for C++ to capture that case: a function definition that can be shared through a header file in several compilation units. C99 that adopted that concept (modifying it slightly).

    static member objects pose indeed more of a problem. The syntax on how to instantiate these guys is quite obscure, especially for template classes or structs. If you'd like to know about that one you'd have to ask for that, tagged specifically with C++.