What is the purpose of ‘extern’ in C++?

In C++, the keyword extern is used to declare a variable or a function that is defined elsewhere, rather than in the current file. It informs the compiler that the variable or function is defined in another file, and its definition will be found during the linking phase.

Specifically, extern can have the following several effects:

  1. Declaring global variables: When declaring a global variable using the extern keyword in a file, it informs the compiler that the variable is defined in another file and can be used in the current file.
  2. Declare a global function: When a global function is declared in a file using the extern keyword, it informs the compiler that the function is defined in other files and can be called in the current file.
  3. Using external variables: when declaring an external variable with the “extern” keyword within a function, it informs the compiler that the variable is defined in another file and can be used in the current function.

It is important to note that extern is just a declaration, not a definition. It simply informs the compiler of the existence of variables or functions without allocating memory space for them. Therefore, when using extern declaration, the definition of the variable or function should be provided elsewhere.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds