Usage of extern in C Language
In the C language, the extern specifier is used before the declaration of a variable or function to indicate that "this variable/function is defined elsewhere and needs to be referenced here."
-
externfor variable declarations. For example, if filea.cneeds to reference the variableint vfromb.c, you can declareextern int vina.c, and then you can referencev. It's important to note that the linkage property of the referenced variablevmust be external. This means that fora.cto referencev, it doesn't just depend on declaringextern int vina.c, but also onvitself being accessible. This touches upon another topic in C language — variable scope. Variables that can be referenced by other modules using theexternspecifier are usually global variables. Another very important point is thatextern int vcan be placed anywhere ina.c. For instance, you can declareextern int vat the beginning of thefunfunction definition ina.c, and thenvcan be referenced, though only within the scope of thefunfunction. This is still a matter of variable scope. Many people have concerns about this, as ifexterndeclarations can only be used at file scope. -
externfor function declarations. Essentially, there is no difference between variables and functions. A function name is a pointer to the beginning of the function's binary block. If filea.cneeds to reference a function fromb.c, for example, if its prototype inb.cisint fun(int mu), then you can declareextern int fun(int mu)ina.c, and then usefunfor anything. Just like variable declarations,extern int fun(int mu)can be placed anywhere ina.c, not necessarily only within the file scope ofa.c. The most common way to reference functions from other modules is to include header files containing their declarations. What's the difference between usingexternand including header files to reference functions? Theexternmethod of referencing is much more concise than including header files! The usage ofexternis straightforward: declare whichever function you want to reference withextern. This is probably an embodiment of the KISS principle! A clear advantage of doing this is that it speeds up the compilation (more precisely, the pre-processing) process, saving time. In the compilation of large C programs, this difference is very noticeable. -
Furthermore, the
externspecifier can be used to indicate the calling convention for C or C++ functions. For example, when calling C library functions in C++, you need to declare the functions to be referenced usingextern "C"in the C++ program. This is for the linker, telling it to use the C function calling convention during linking. The main reason is that C++ and C programs have different naming conventions in the object code after compilation.