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 OverflowAssuming 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
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
Most elegant / best practice for global variable
c - Use of global variables in Embedded Systems - Electrical Engineering Stack Exchange
When is it ok to use a global variable in C? - Stack Overflow
When are global variables "okay"?
How to Declare Global Variable in C?
Can I change the value of a global variable in C?
Can global variables be constant in C?
Videos
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
externin a header included by all modules who need those variables.group them in a
structand declare that struct asexterngroup 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,
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.
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; } /* ... */ }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; /* ... */ } }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.
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.
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?
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."
I'm working on a hobby game engine where various systems access global resources. These resources are singletons in the sense that there should never be more than one instance of them.
Is there any reason why I should not just declare these global variables?
I've heard "don't use globals" too many times, but it seems like it makes sense my scenario.
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