Search code examples
clinkage

Theoretically can using external linkage and including header files replace each other?


External linkage provides scoping across compilation units.

Theoretically, can using external linkage replace including header files where they are used?

I don't mean to do that, and just ask for better understanding the concepts.

Conversely, can including header files where the declarations in them are used replace external linkage?

Do external linkage and header files have a lot of overlap in their use cases?

Thanks.


Solution

  • Linkage is a property of identifiers. The details of the declaration(s) of an identifier determine its linkage within the scope of that declaration, thus you don't have linkage (or identifiers in the first place) without declarations.

    Header files are primarily a way to share declarations, so no, external linkage is not an alternative to header files. The two aren't even really comparable. Indeed, the identifiers declared in a header file typically do include some with external linkage, so external linkage and header files are not mutually exclusive.

    Now, you can put whatever declarations you want directly in your source files, instead of (or in addition to) obtaining them by #includeing headers. This includes not only declarations of of identifiers with external linkage but also declarations of identifiers that always have no linkage, such as typedef names, enums, and structure tags. Perhaps that's what you meant. The practice scales poorly, however, even when you have only a handful of source files among which to share declarations.