Assuming your variable is global and non static.

You need to declare it in a header file. We use extern keyword for this. As pointed out in comments, this keywords is not necessary, but most C users prefer to use it in headers, this is a convention.

stackoverflow.h:

#ifndef STACHOVERFLOW_H
#define STACHOVERFLOW_H

extern int my_var;

#ifndef

And you initialize it in source file. (Use of keyword extern is prohibited if you want to provide an initialization value).

stackoverflow.c

#include "stackoverflow.h"

int my_var = 50;

Do not put initialization value in a header, or you will get a linker error if the header is used at least twice.

Now you can use your variable in any other module by including the header.

main.c

#include <stdio.h>
#include "stackoverflow.h"

int main()
{
    printf("my_var = %d\n", my_var);
    return 0;
}

Including header "stackoverflow.h" in "stackoverflow.c" is a way to get sure definitions in source file match declarations in header file. This permit to have errors as soon as compilation instead of sometimes cryptic linker errors.

Edit: This is not at all the way to make a variable "private". You have to use a static variable to make it "private". See R Sahu's answer

Answer from jdarthenay on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ global-variables-in-c
Global Variables in C - GeeksforGeeks
The global variables get defined outside any function- usually at the very beginning/top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that ...
Published ย  July 23, 2025
Top answer
1 of 6
6

Assuming your variable is global and non static.

You need to declare it in a header file. We use extern keyword for this. As pointed out in comments, this keywords is not necessary, but most C users prefer to use it in headers, this is a convention.

stackoverflow.h:

#ifndef STACHOVERFLOW_H
#define STACHOVERFLOW_H

extern int my_var;

#ifndef

And you initialize it in source file. (Use of keyword extern is prohibited if you want to provide an initialization value).

stackoverflow.c

#include "stackoverflow.h"

int my_var = 50;

Do not put initialization value in a header, or you will get a linker error if the header is used at least twice.

Now you can use your variable in any other module by including the header.

main.c

#include <stdio.h>
#include "stackoverflow.h"

int main()
{
    printf("my_var = %d\n", my_var);
    return 0;
}

Including header "stackoverflow.h" in "stackoverflow.c" is a way to get sure definitions in source file match declarations in header file. This permit to have errors as soon as compilation instead of sometimes cryptic linker errors.

Edit: This is not at all the way to make a variable "private". You have to use a static variable to make it "private". See R Sahu's answer

2 of 6
5

which place is better to declare a global variable in c program

Answer: In source(*.c) file.

Assume the scenario like, I have declared a variable in a header file. I included this header in two different .c files. After the macro expansion step of compilation, these two files will have the global variable with the same name. So it will throw an error like multiple declarations of the variable during the linking time.

Conclusion:-

Keep all global variable declaration on .c file and put it as static if it is doesn't need in other files.

Add extern declaration of the variable in the corresponding header file if it's needed to access from other files

Discussions

Most elegant / best practice for global variable
essentially variables that control the verbosity of error messages, some initial conditions that can be set up (and never changed thereafter etc). Surely all of that can just be local to the translation unit responsible for performing logging? That translation unit can have an API that doesn't expose that state directly. You don't even necessarily need to provide a way to retrieve the state. Setting it up once in some kind of log_init function would be sufficient. I don't have a big problem with global variables for things that are supposed to represent globally accessible state โ€” the standard stream file handles are a good example of this. But what you are describing doesn't seem like something that needs to be "globally accessible" anyway. Only one small part of your code cares about it. More on reddit.com
๐ŸŒ r/C_Programming
5
2
July 5, 2023
c - Use of global variables in Embedded Systems - Electrical Engineering Stack Exchange
I started writing firmware for my product and I'm a rookie here. I went through many articles about not using global variables or functions. Is there any limit for using global variables in an 8 bit More on electronics.stackexchange.com
๐ŸŒ electronics.stackexchange.com
January 22, 2014
When is it ok to use a global variable in C? - Stack Overflow
Apparently there's a lot of variety in opinions out there, ranging from, "Never! Always encapsulate (even if it's with a mere macro!)" to "It's no big deal โ€“ use them when it's more More on stackoverflow.com
๐ŸŒ stackoverflow.com
When are global variables "okay"?
The rule of thumb that I use is: try to imagine both cases. The case where you use globals and the case where you donโ€™t. Then fast forward a year. Which case is easier to understand and maintain. Which case is simpler to relearn. That case is usually the one to go with. The other part of the equation is, which case is less error prone to maintain. More on reddit.com
๐ŸŒ r/C_Programming
34
32
July 18, 2021
People also ask

How to Declare Global Variable in C?
A global variable in C is declared outside of all functions, usually at the top of the program, so it can be accessed by all functions.
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ global-variables
Global Variables in C Programming (With Examples)
Can I change the value of a global variable in C?
Yes, global variables can be modified by any function in the program.
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ global-variables
Global Variables in C Programming (With Examples)
Can global variables be constant in C?
Yes, you can declare a global variable as const to prevent modification, like const int MAX_LIMIT = 100;.
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ global-variables
Global Variables in C Programming (With Examples)
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_scope.php
C Variable Scope
If you operate with the same variable name inside and outside of a function, C will treat them as two separate variables; One available in the global scope (outside the function) and one available in the local scope (inside the function):
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ most elegant / best practice for global variable
r/C_Programming on Reddit: Most elegant / best practice for global variable
July 5, 2023 -

Hi,

I have been working as a hobbyist on a multi threaded C program where I have usage of global variables: essentially variables that control the verbosity of error messages, some initial conditions that can be set up (and never changed thereafter etc).

I was wondering on how is the best way to implement that, I have used the following approaches:

  • declare them as extern in a header included by all modules who need those variables.

  • group them in a struct and declare that struct as extern

  • group them in a struct and pass a pointer to that struct to all functions that need those variables.

The latter solution seems cleaner, but is quite heavy to implement, as basically you need to pass the pointer reference to many functions.

Now, since global variables are usually frowned upon but less so for variables like the above ones (unlikely to be changed, used as read-only, etc.) I was thinking what is the approach you guys recommend or use in your code?

Thanks,

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ cprogramming โ€บ c global variables
Global Variables in C
June 10, 2012 - Value of Global variable g = 10 ... value of Global variable g = 30 ยท Global variables are available to only those functions that are defined after their declaration....
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ c-programming โ€บ global-variables
Global Variables in C Programming (With Examples)
6 days ago - Learn in this tutorial about C global variables with examples. Understand their scope, usage, benefits, and limitations. Read now!
Find elsewhere
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ what is global variable in c?
What is Global Variable in C? - Scaler Topics
May 21, 2024 - A variable defined outside the scope of all the functions is known as a global variable in C. The global variables have a global scope, hence these variables can be accessed and modified by any function, structure, or in any scope in C. Global ...
๐ŸŒ
Code Quoi
codequoi.com โ€บ en โ€บ local-global-static-variables-in-c
Local, Global and Static Variables in C - codequoi
Then it can modify the value stored at that address. This is why when main later reads the value of this variable, it will have changed. When we declare a variable outside of any function, it is a global variable. This means that it is accessible in any function of the program.
๐ŸŒ
Testbook
testbook.com โ€บ home โ€บ gate โ€บ global variable in c: usage, examples, redefinition & practice problems
Global Variable in C: Usage, Examples, Redefinition & Practice Problems
Global variables are defined outside all functions, usually at the top of a program. Once declared, these variables retain their values throughout the program's lifespan and can be accessed within any function defined in the program.
๐ŸŒ
BYJUS
byjus.com โ€บ gate โ€บ global-variable-in-c
Use of the Global Variable in C
September 20, 2022 - The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.
๐ŸŒ
Quora
quora.com โ€บ Can-I-declare-a-global-variable-in-the-main-C
Can I declare a global variable in the main C++? - Quora
Avoid cross-TU initialization dependencies; prefer function-local statics for complex objects. Ensure proper synchronization for concurrent access. Keep globals minimal, immutable where possible, and well-documented. ... Yes of course you can declare global variables in C++.
Top answer
1 of 6
36

You can use global variables successfully, as long as you keep in mind @Phil's guidelines. However, here are some nice ways to avoid their issues without making the compiled code less compact.

  1. Use local static variables for persistent state that you only want to access inside one function.

    #include <stdint.h>
    void skipper()
    {
        static uint8_t skip_initial_cycles = 5;
        if (skip_initial_cycles > 0) {
            skip_initial_cycles -= 1;
            return;
        }
        /* ... */
    }
    
  2. Use a struct to keep related variables together, to make it clearer where they should be used and where not.

    struct machine_state {
         uint8_t level;
         uint8_t error_code;
    } machine_state;
    
    struct led_state {
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    } led_state;
    
    void machine_change_state()
    {
        machine_state.level += 1;
        /* ... */
        /* We can easily remember not to use led_state in this function. */
    }
    
    void machine_set_io()
    {
        switch (machine_state.level) {
        case 1:
            PIN_MACHINE_IO_A = 1;
            /* ... */
        }
    }
    
  3. Use global static variables to make the variables visible only within the current C file. This prevents accidental access by code in other files due to naming conflicts.

    /* time_machine.c */
    static uint8_t current_time;
    /* ... */
    
    /* delay.c */
    static uint8_t current_time; /* A completely separate variable for this C file only. */
    /* ... */
    

As a final note, if you are modifying a global variable within an interrupt routine and reading it elsewhere:

  • Mark the variable volatile.
  • Make sure it is atomic for the CPU (i.e. 8-bit for an 8-bit CPU).

OR

  • Use a locking mechanism to protect access to the variable.
2 of 6
27

The reasons you would not want to use global variables in an 8-bit system are the same you would not want to use them in any other system: they make reasoning about the program's behavior difficult.

Only bad programmers get hung up on rules like "don't use global variables". Good programmers understand the reason behind the rules, then treat the rules more like guidelines.

Is your program easy to understand? Is its behavior predictable? Is it easy to modify parts of it without breaking other parts? If the answer to each of these questions is yes, then you are on the way to a good program.

Top answer
1 of 16
67

Variables should always have as small a scope as possible. The argument behind this is that every time you increase the scope, you have more code that potentially modifies the variable, thus more complexity is induced in the solution.

It is thus clear that avoiding using global variables is preferred if the design and implementation naturally allow that. Due to this, I prefer not to use global variables unless they are really needed.

I can not agree with the 'never' statement either. Like any other concept, global variables are something that should be used only when needed. I would rather use global variables than using some artificial constructs (like passing pointers around), which would only mask the real intent.

Some good examples where global variables are used are singleton pattern implementations or register access in embedded systems.

On how to actually detect excessive usages of global variables: inspection, inspection, inspection. Whenever I see a global variable I have to ask myself: Is that REALLY needed at a global scope?

2 of 16
22

The only way you can make global variables work is to give them names that assure they're unique.

That name usually has a prefix associated some some "module" or collection of functions for which the global variable is particularly focused or meaningful.

This means that the variable "belongs" to those functions -- it's part of them. Indeed, the global can usually be "wrapped" with a little function that goes along with the other functions -- in the same .h file same name prefix.

Bonus.

When you do that, suddenly, it isn't really global any more. It's now part of some module of related functions.

This can always be done. With a little thinking every formerly global variable can be assigned to some collection of functions, allocated to a specific .h file, and isolated with functions that allow you to change the variable without breaking anything.

Rather than say "never use global variables", you can say "assign the global variable's responsibilities to some module where it makes the most sense."

๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Global_variable
Global variable - Wikipedia
January 5, 2026 - In compiled languages, global variables are generally static variables, whose extent (lifetime) is the entire runtime of the program, though in interpreted languages (including command-line interpreters), global variables are generally dynamically allocated when declared, since they are not ...
๐ŸŒ
University of Texas
farside.ph.utexas.edu โ€บ teaching โ€บ 329 โ€บ lectures โ€บ node19.html
Global variables
The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ still not sure when to use global variables
r/C_Programming on Reddit: Still not sure when to use global variables
February 17, 2022 -

I did the Advent of Code 2021 in C and I'm reviewing my code from it. In the beginning I wasn't using global variables because i didn't need to, but later I had to manage arrays of pointers and because they were always being passed as arguments to other functions, I decided to make them global. Most functions were receiving and returning void because of that.

Then I got into this mindset of "never use global variables" and I was able to make programs without any global variable, but the functions would have lots of parameters, many variables were passed all the time, and I had to use triple pointers for that. I personally think that's even more unsafe and unreadable than just using a global variable, but everyone always says to not use them. I'm trying to refactor the code and I don't know whether I should use or not global variables.

I know the readability and the code itself are bad, maybe I could've used some known algorithms... I'm just using this one as an example: Day 12

๐ŸŒ
Quora
quora.com โ€บ In-what-case-does-declaring-a-global-variable-in-C-C-become-justifiable
In what case does declaring a global variable in C/C++ become justifiable? - Quora
Answer (1 of 4): When: 1. You know you only need one (or a small, known count, possibly) 2. It is used in many places. 3. It is used in an intermittent fashion, so passing it around to the places that actually needs it is a pain. 4. It is clearly defined what operations are done on the variable,...
๐ŸŒ
PrepBytes
prepbytes.com โ€บ home โ€บ c programming โ€บ global variable in c
Global Variable in C
January 8, 2024 - In C programming, a global variable is a variable that is declared outside any function and is accessible throughout the entire program. Unlike local variables, which are confined to the scope of a specific function, global variables retain ...