Add its declaration to some .h file that is included in both .c files. Define it in one of the files.
Of course, it can't be declared static
for this to work since the static
keyword is a promise that the name won't be needed outside of that particular module.
For example, in prog.h
:
extern char *Foo;
in prog.c
:
#include "prog.h"
#include "log.c"
#include "library.c"
char * Foo; // make sure that Foo has a definition
// some code probably wants to make Foo have a value other than NULL
in log.c
:
//... other includes
#include "prog.h" // and now Foo is a known name
// some code here is using the global variable Foo
Now, for the bad news.
Doing this sort of thing creates a coupling between the prog.c
and log.c
modules. That coupling adds to the maintenance cost of your application as a whole. One reason is that there is no way to prevent other modules from using the global variable also. Worse, they might be using it completely by accident, because its name is insufficiently descriptive.
Worse, globals make it much more difficult to move from single-threaded programs to multi-threaded programs. Every global variable that might be accessed from more than one thread is a potential source of really hard to diagnose bugs. The cure is to guard information that must be global with synchronization objects, but overused that can result in an application where all the threads are blocked except the one that is currently using the global, making the multi-threaded application effectively single threaded.
There certainly are times when the inter-module coupling implied by global variables is acceptable. One use case is for general purpose application-wide options. For instance, if your application supports a --verbose
option that makes it chatter while it works, then it makes sense for the flag that is set by the option and tested throughout the code would be a global variable.
There are certainly questions at SO that delve deeply into the pitfalls of globals and will provide guidance on their sensible use.