I want to share the value of sizeof(array)
between two .c modules. The array is initialized in file A, so compiler knows the size at compile time and then I want to use the size of this array in another B file.
Example:
In A.c file:
int arr[] = {1, 2, 3};
.
.
.
for (int i = 0; i < sizeof(arr); i++); // that works
In A.h file:
extern int arr[];
In B.c file:
#include "A.h"
.
.
.
for (int i = 0; i < sizeof(arr); i++); // here compiler doesn't know size of this arr
Is there a way to make this work? I know why this doesn't work but maybe there is a sneaky trick to workaround this.
Is there a way to make this work? I know why this doesn't work but maybe there is a sneaky trick to workaround this.
This is not very sneaky, but it works...
In some.h
//declare as extern for project global scope
extern int arr[];
extern size_t gSizeArray;
Then in some.c
//define and initialize extern variables in 1 (and only one) .c file,
int arr[] = { 1,2,3 };
size_t gSizeArray = sizeof(arr)/sizeof(arr[0]);
In someother.c
that includes some.h
#include "some.h"
//you can now see the value of gSizeArray in this file
printf("%zu\n%d,%d,%d\n", gSizeArray, arr[0], arr[1], arr[2]);//should output
3
1,2,3
caveat
The value of using an extern in this fashion is that the value of that variable can change in one module, and that same value can be seen in any .c
file that includes some.h
corollary
The problem of using an extern in this fashion is that the value of that variable can change in one module, and that same value can be seen in any .c
file that includes some.h
.
(or in other words, be careful. Globals, in particular extern
globals can be helpful, but they can also be dangerous. Particularly for maintainers of the code who are not also the author of the code, who may not be aware a variable is of extern
scope, and use it unwittingly in inappropriate ways.
By the way, there is probably more than you'll ever want to know about using extern scope in this post.