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.
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.