Here's my problem: I have a big main.c file containing 40 or so "global" structures in my program (they are declared at the begining on the files), I also have several functions in my main.c file that I are able to directly read and write into these structures since they are global. Now I'm trying to move several function of my original main.c file into another .c file that would contain only the functions related to a specific part of my program. But of course I cannot directly access the main.c global variables from my new .c file. Is there a way around this? I'd like to avoid passing every structure by pointer as this would get horrible function prototypes. thanks
Move the global structure definitions into a header (.h) file and just #include
your header in each c file that needs to access those structures. Any global variables can be declared extern
and then defined in your main.c.
Global.h
// WARNING: SHARING DATA GLOBALLY IS BAD PRACTICE
#ifndef GLOBAL_H
#define GLOBAL_H
//Any type definitions needed
typedef struct a_struct
{
int var1;
long var2;
} a_struct;
//Global data that will be defined in main.c
extern a_struct GlobalStruct;
extern int GlobalCounter;
#endif
main.c
#include "Global.h"
#include "other.h"
#include <stdio.h>
int GlobalCounter;
a_struct GlobalStruct;
int main(int argc, char *argv[])
{
GlobalCounter = 5;
GlobalStruct.var1 = 10;
GlobalStruct.var2 = 6;
printf("Counter: %d\nStruct [ var1: %d var2: %ld ]\n",
GlobalCounter, GlobalStruct.var1, GlobalStruct.var2);
do_other_stuff();
printf("Counter: %d\nStruct [ var1: %d var2: %ld ]\n",
GlobalCounter, GlobalStruct.var1, GlobalStruct.var2);
return 0;
}
other.h
#ifndef OTHER_H
#define OTHER_H
void do_other_stuff(void);
#endif
other.c
#include "other.h"
#include "Global.h"
void do_other_stuff(void)
{
GlobalCounter++;
GlobalStruct.var1 = 100;
GlobalStruct.var2 = 0xFFFFFF;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With