1

I wrote a c program with some global variables, and most functions use and modify those global variables. Then I decide to split this program into a c file and multiple header files. How do I deal with the global variables in the program?

Should I put them in the .c file? Or in the relevant .h files?

Thanks for helping!

Yige Song
  • 333
  • 6
  • 16

3 Answers3

3

Global variables are someway dangerous but in some cases we need them. try not to use global variables as a general tip. global variables can be declared in c file and externed in h file. for example: lets assume that we declared in foo.c file global variable:

int g_variable = 0;

now in foo.h, we need to write

extern int g_variable;

for extending the scope of this variable for the whole program. now evrey h file that includes foo.h can access g_variable!

Adam
  • 2,820
  • 1
  • 13
  • 33
1

If you need to use the global variable in multiple places, use an extern global variable. See Shared Global Variables in C.

If you only need it inside of a single .c file, then define it only in that .c file and mark it static.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
1

Global declarations should go in an .h file, e.g.:

h.h:

extern int x; //extern here means: declare x without reserving storage

and global definitions in a .c file, e.g.:

c.c:

#include "h.h" //to verify consistency
int x = 42; //reserve storage for x
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142