I have a data structure that I want to share globally between files in the project.
mystruct_s data[] = {
{ // element 1
}, { // element 2 ...
}, { 0 } // element N is zero to mark array end
}
Within the same file, objects refer to data
. Its type is read as mystruct_s[N]
. This is nice and straighforward.
In the header file, I have:
mystruct_s data[];
In other files, I get a type mismatch warning, because it is assumed to mean a 1-element array.
I am counting length based on array contents, so I don't need to know sizeof
. A good old fashioned pointer mystruct_s*
would do.
data[]
there too.)My preferred way to declare global variables and make them known in other modules is as follows:
// to define global variables, use the following:
// module.c
#include "glo.h"
// glo.h
#ifndef EXTERN
# define EXTERN extern
#endif
EXTERN int myvar;
#define ARR_SIZE 123
EXTERN int myArr[ARR_SIZE];
// main.c
#define EXTERN
#include "glo.h"
This alocates storage for the globals in main
and makes them known as extern
in all other modules.
This expands to:
// module.c
extern int myvar;
extern int myArr[123];
and in main:
// main.c allocates storage
int myvar;
int myArr[123];
EDIT
You have a requirement to know the array size not through a defined constant but as the size of the array based on the initializers.Possibly a good way is to define the array with a dummy size for all other modules and to provide the array size as a separate global variable that you initialize in main, after the initialization.
// glo.h
#ifndef EXTERN
# define EXTERN extern
extern int myArr[2];
#endif
EXTERN int gArrSize;
and:
// main.c
#define EXTERN
#include "glo.h"
int myArr[] = { 1, 2, 3, 4, 0};
int gArrSize= sizeof(myArr)/sizeof(myArr[0]);