Using a Global Variable
suggest changeUse of global variables is generally discouraged. It makes your program more difficult to understand, and harder to debug. But sometimes using a global variable is acceptable.
#ifndef GLOBAL_DOT_H /* This is an "include guard" */
#define GLOBAL_DOT_H
/**
* This tells the compiler that g_myglobal exists somewhere.
* Without "extern", each inclusion is a tentative definition.
* More than one external definition of g_myglobal in the program
* is undefined behavior. Don't miss this!
*/
extern int g_myglobal; /* _Declare_ g_myglobal, that is promise it will be _defined_ by
* some module. */
#endif /* GLOBAL_DOT_H */
#include "global.h" /* Always include the header file that declares something
* in the C file that defines it. This makes sure that the
* declaration and definition are always in-sync.
*/
int g_myglobal; /* Define g_myglobal. A file-scope object is initialized to 0
* at program startup. */
#include "global.h"
int main(void)
{
g_myglobal = 42;
return 0;
}
See also How do I use extern to share variables between source files?
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents