askvity

How to Define a Global Variable in a Function in C?

Published in Global Variables 4 mins read

To use a global variable within a function in C, you don't define it inside the function, but rather you declare it. The actual definition (where memory is allocated) occurs outside any function, typically at the top of a .c file. Inside the function, you use the extern keyword to signal that the variable is defined elsewhere.

Understanding Global Variables in C

A global variable is a variable declared outside of any function. It has global scope, meaning it is accessible from any function within the same file or even from other files in the project.

Defining and Declaring Global Variables

Here's a breakdown with an example:

  1. Definition (Outside any function): This is where the variable is actually created and memory is allocated for it. This happens only once in your entire program.

    // File: my_file.c
    int global_variable = 10;  // Definition: memory is allocated and initialized
  2. Declaration (Inside a function or in another file): This informs the compiler that the variable exists and is defined elsewhere. It doesn't allocate memory. This is where you use the extern keyword.

    // File: another_file.c
    
    #include <stdio.h>
    
    extern int global_variable; // Declaration: informs the compiler
    
    void my_function() {
        printf("Value of global_variable: %d\n", global_variable);
        global_variable = 20; // You can modify the global variable here
        printf("Value of global_variable after modification: %d\n", global_variable);
    }

The Role of extern

The extern keyword is crucial. It tells the compiler: "This variable exists, but it is defined in another file or elsewhere in this file." Without extern, the compiler would assume you're trying to define a new, local variable with the same name, leading to errors (like multiple definitions) when you link your program.

According to the reference, the syntax to declare a global variable in C is:

extern DataType varName;

Example Demonstrating Global Variables Across Multiple Files

Let's expand on the provided example from the reference to illustrate how to use global variables across multiple .c files:

File: glob1.c

#include <stdio.h>

extern void print(void); // Function prototype for print() defined in glob2.c

int a, b;
float c, d;

int main(int argc, char *argv[]) {
    a = 2;
    b = 3;
    printf("a = %d, b = %d\n", a, b);
    c = 2.0;
    d = 3.0;
    printf("c = %f, d = %f\n", c, d);
    print(); // Calls print() in glob2.c
    return 0;
}

File: glob2.c

#include <stdio.h>

extern int a, b;
extern float c, d;

void print(void) {
    printf("Inside print() function from glob2.c:\n");
    printf("a = %d, b = %d\n", a, b);
    printf("c = %f, d = %f\n", c, d);
}

Explanation:

  • glob1.c defines the global variables a, b, c, and d.
  • glob1.c declares the function print() defined in glob2.c.
  • glob2.c uses extern to declare that a, b, c, and d are defined elsewhere (in glob1.c). This allows glob2.c to access and use these global variables.
  • To compile the code, you typically use a command like: gcc glob1.c glob2.c -o myprogram

Key Considerations

  • Scope: Global variables have program scope, so changes made to them in one function will be visible in all other functions that have declared them using extern.
  • Initialization: It's good practice to initialize global variables when they are defined. If you don't explicitly initialize them, they are initialized to zero by default.
  • Header Files: For larger projects, it's common to put extern declarations in a header file that is then included in any .c file that needs to access the global variables. This ensures consistency and avoids errors.
  • Avoid Overuse: While global variables can be convenient, excessive use can lead to code that is difficult to maintain and debug. Consider using other techniques like passing data as function arguments or using structures to group related data.

Related Articles