C| |Why are only declared in the header file and not defined, and the class definition can be placed in the header file

Why are only declared but not defined in the header file, while the class definition can be placed in the header file


We must first understand a few basic concepts:

Compilation unit

For the C language, each .c file is a compilation unit. Only in terms of compilation, there is no connection between the various compilation units

 

Unresolved symbol table

Provides the address of a symbol that is referenced in this compilation unit, but is not defined in this compilation unit (the owner is the compilation unit)

 

Export symbol table

Provides symbols and addresses that this compilation unit has definitions and can be used by other compilation units (the owner is the compilation unit)

 

After the .c file is compiled, each compilation unit will generate two tables, the unresolved symbol table and the exported symbol table

 

link

When linking, each compilation unit will look up the symbols in its unresolved symbol table from the exported symbol tables of other compilation units.

If unresolved symbols in the symbol table are found in other compilation units, report

If not found, which unresolved symbols will enter the unresolved symbol table.

 

external

extern tells the compiler that the definition of this symbol is in another compilation unit, and the symbol will be placed in the unresolved symbol table

 

static

Static tells the compiler that the symbol of this variable or function is only used in the compilation unit and not in the export symbol table. That is, you can’t see it when you link

 

For classes, when linking, the default is internal link, which is static; while the function defaults to external link, the function name will be placed in the export symbol table, so when the function wants to be called only internally, add the modifier static

 

【problem】:

  1. Generally, the header file only declares the reason why it is not defined

If there is a variable definition in a header file, when the header file is included by multiple .c files, the duplicate definition will be found in the export symbol table of different compilation units when linking, and an error will be reported

  1. Reasons why classes can be defined in header files

The definition of the class is static by default, internal linkage, invisible in other compilation units, even if it is repeatedly included

 

Guess you like

Origin blog.csdn.net/qq_40399012/article/details/84069983