0

I have a number of modules in a C program for a microcontroller not running any OS. Each module has its own type definitions, enumerations, and data structre definitions to represent the module's status and I think it would be neat to define them in the module's associated header file.

Then, I have a global variable defined in global_var.c to "remember" the current status of the whole system. Since the modules' data structures are being referred to in the global variable's definition, all the module headers are being included in global_var.h.

However, these modules will also need to access the global variable thus they will need to include global_var.h as well.

How can I avoid mutual inclusion of the header files if I really want to keep my global variable?

Many thanks!

global_var.h

#ifndef GLOBAL_VAR_H
#define GLOBAL_VAR_H
#include "module.h"

typedef struct GLOBAL_STRUCTURE {
    module_structure m;        
} global_structure;
#endif

global_var.c

#include "global_var.h"
global_structure gs;

module.h

#ifndef MODULE_H
#define MODULE_H
typedef struct MODULE_STRUCTURE {
    int a;
} module_structure;

void module_function(void);
#endif

module.c

#include "global_var.h"
extern global_structure gs;

void module_function(void) {
    gs.m.a=0;
}

2 Answers2

0

I think the C language is supposed to share a global defined twice. but it depends on the compiler (well linker) as to whether your toolchain actually does that I have had some that do and some that dont. The safest route is to only declare the variable once and everywhere else explicitly declare it as extern. You will often see this done like this:

common.h

#ifundef HELLO
#define HELLO
#endif
HELLO unsigned int myglobx;

one.c

#include "common.h"

two.c

#include "common.h"

three.c

#define HELLO extern
#include "common.h"
old_timer
  • 69,149
  • 8
  • 89
  • 168
0

Try this: In Module.c #define XYZ

then in Module.h

    #define MODULETYPE
    #ifdef XYZ
     MODULETYPE 

    #else
    MODULETYPE extern
   #endif
   MODULETYPE  int var1,var2;

Do this for every module and include your header wherever you want.

Vagish
  • 2,520
  • 19
  • 32