#include into multiple sources

if i have a set of variables listed in an include file and I want to use them in multiple source files how do I need to structure the include file.

Currently I am using #include <MYFILE> statement in both .c files and i get linking errors stating that I have redefined. And if I only include in one source the other source is lacking the variables.
Last edited on
Do not define variables in a header file.

Only define them in ONE source file, then in the header file put something like this:

1
2
extern int g_somevar;
extern int g_someothervar;


I prefixed it with g_ to indicate that it is global (and hopefully avoid name conflicts).
Thank you. That all that was needed.
To avoid having to duplicate variable declarations (once in the header, once in a .cpp file), you can use a trick with macros:

1
2
3
4
5
6
// globals.cpp

#define GLOBAL
#include "globals.h"

 // -- can leave rest of file empty 

1
2
3
4
5
6
7
8
// globals.h

#ifndef GLOBAL
#define GLOBAL extern
#endif

GLOBAL int g_somevar;
GLOBAL int g_someothervar;


Though it's worth noting that globals should be avoided most of the time because they lead to sloppy, unorganized, hard to follow code that is not easily reusable.
Topic archived. No new replies allowed.