C++: Internal and External Linking During Project Compilation

File creation and compilation:

In the process of compiling a C++ project, each cpp file is compiled separately, and the object files generated by the compilation are linked with each other, and the functions and global variables contained therein have external links and internal links (also called static links) by default. Therefore, the variables and functions in this source file can be used in other source files. To cancel external links, use internal links, you can use the Static keyword, or use anonymous namespaces, namespace{ … }. To add external links, you can use the extern keyword. This keyword is only a declaration of a variable, and does not open up memory space for the variable. Of course, you can define the variable at the same time as the variable is declared.

Although the object files generated after compilation are linked with each other, in a single file, references to functions and variables within a function need to be linked internally. (So ​​you need to declare an external variable or function inside this file, or include the corresponding header file) (For external variables, only declarations do not need to be defined. If they are defined, a redefinition error will occur, so you need to use the external declaration keyword extern)

So: the role of the header file is to add declarations of external variables or functions. When the header file is not included in the program, the header file does not participate in the compilation process, but the compiler compiles each source file. The header file only participates in the preprocessing process of program compilation. #include is a preprocessing macro. During the preprocessing process, the program will expand the header file.

const and typedef are internal linkage by default and can be modified to external linkage using extern.

The header file contains the definition of the variable, and the header file is included in multiple places will cause redefinition. You can use the Static keyword to make a variable only have internal linkage properties, so that each source file that includes this header file has a static copy of the variable, and this copy can be manipulated independently in each source file without interfering with each other. . This usage of Static also applies to functions. However, where this header file is not included, and other source files cannot use these variables and functions that have been defined as internal links after compiling and generating object files, that is, they do not participate in the process of linking each other between object files.

 

Among them, global variables and static variables are initialized before the program enters main, and are initialized in the order in which they appear.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562865&siteId=291194637