initialized and declared extern
When a variable is declared as extern, it means that the variable is defined elsewhere in the program. This declaration allows the variable to be used in multiple source files without causing a linker error.
To initialize and declare an extern variable, you need to perform the following steps:
-
Define the
externvariable in a header file: Create a header file (e.g., "example.h") and declare the variable using theexternkeyword. For example:// example.h extern int myVariable; -
Include the header file in the source files where you want to use the
externvariable. For example:// main.c #include "example.h" int main() { // Use the extern variable myVariable = 10; // Rest of the code return 0; } -
Define the
externvariable in one of the source files: Choose one of the source files (e.g., "example.c") and define theexternvariable without theexternkeyword. For example:// example.c int myVariable; // Definition of the extern variable
By following these steps, you can initialize and declare an extern variable in your program. Remember that the variable should be defined in only one source file to avoid multiple definitions and linker errors
原文地址: https://www.cveoy.top/t/topic/ikfq 著作权归作者所有。请勿转载和采集!