Home > Backend Development > C++ > body text

How to use extern in c language

下次还敢
Release: 2024-04-29 20:18:16
Original
559 people have browsed it

The extern keyword is used to declare variables or functions defined in other files. Using extern can achieve modular programming, avoid repeated definitions and reduce compilation time, but it should be noted that the extern declaration only declares the existence of a variable or function, not its definition and initialization.

How to use extern in c language

Usage of extern in C language

The role of extern keyword

The extern keyword is used to declare a variable or function, indicating that the variable or function is defined in other files (modules), telling the compiler that when the variable or function is used in the current module, its definition can be found elsewhere .

Usage

Declare an extern variable:

<code class="C">extern int var;</code>
Copy after login

Declare an extern function:

<code class="C">extern int func();</code>
Copy after login

Advantages

  • Modular programming: The extern keyword can divide the code into different modules to achieve modular programming and improve code maintainability.
  • Avoid repeated definitions: When multiple modules need to use the same variables or functions, using extern can avoid repeated definitions in each module and avoid naming conflicts.
  • Reduce compilation time: Because extern declarations do not actually define variables or functions, they can reduce compilation time, especially for large projects.

Notes

  • When extern declares a variable, it only allocates memory space and does not initialize the variable. Therefore, the variable must be initialized before using it.
  • Before using a function declared by extern, you need to ensure that the function is defined and compiled in other modules. Otherwise, the compiler will report an error.
  • The extern declaration only declares the existence of a variable or function, not its definition. Therefore, when using extern-declared variables or functions, you need to ensure that they have the correct type and value.

The above is the detailed content of How to use extern in c language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!