Home > Backend Development > C++ > When Should You Use the `extern` Keyword for Global Variables in C ?

When Should You Use the `extern` Keyword for Global Variables in C ?

Mary-Kate Olsen
Release: 2025-01-04 08:38:35
Original
351 people have browsed it

When Should You Use the `extern` Keyword for Global Variables in C  ?

Declaring Global Variables: When to Leverage the extern Keyword in C

The extern keyword in C plays a crucial role in managing global variables. It enables you to declare the existence of a global variable in multiple source files while defining it only once.

Understanding the Role of extern

The extern keyword informs the compiler about the existence of a global variable. It doesn't provide a definition but simply declares its name and type. By using extern, you can access the variable in other source files without redefining it.

Benefits of Using extern for Global Variables

  • Centralized Declaration: You can declare global variables in a separate header file, making them available to all source files that include that header.
  • Efficient Definition: By defining the global variable only once in one source file, you prevent inconsistencies and confusion.
  • Linker Resolution: The linker combines the object files from multiple source files and resolves references to global variables, ensuring that the defined variable is used everywhere.

Usage Example

Consider the following example:

header.h:

#ifndef HEADER_H
#define HEADER_H

extern int global_x;

void print_global_x();

#endif
Copy after login

source1.cpp:

#include "header.h"

// Define global_x here
int global_x = 5;

int main()
{
    print_global_x();
}
Copy after login

source2.cpp:

#include "header.h"

void print_global_x()
{
    std::cout << global_x << std::endl;
}
Copy after login

In this example, global_x is declared in header.h using extern, making it known to both source1.cpp and source2.cpp. However, it's defined only in source1.cpp, ensuring that it's available for use in both source files.

The above is the detailed content of When Should You Use the `extern` Keyword for Global Variables in C ?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template