I will often wrap a group of related global functions and variables in a struct that makes a kind of "namespace" for them, for example
extern struct foo_namespace {
int (* const foo)(int a);
int (* const bar)(void);
const int a;
const int b;
int x;
int y;
} foo;
Then link it with a .c
file that sets the functions and constants.
This allows me to create global names without worrying about what's in the namespace and what will be later, it is very clean and convenient.
I do worry however that it introduces a small amount of inefficiency in my code by requiring the functions being called through pointers, and there may be other issues as well.
What are all of the potential problems and inefficiencies with grouping globals this way, whether they are problems with program design, speed, executable size, or anything else.
Edit: I just ran a loop with an empty function in a struct, and a regular function. When no optimization was applied the function in the struct was faster (20 vs 26 seconds). After optimization, the global function was totally optimized away and was faster. It would seem that unless the function can be inlined it's not a big deal as far as speed goes
Increase collision potential.
The idea here is to use
foo.a
,foo.x
andfoo.bar()
vs. maybefoo_a
,foo_x
,foo_bar()
. The trouble is nowfoo
collides with any other 3 characterfoo
object/function.The prefix
foo_
approach takes a 5+ character match to collide. IOWs, although OP's idea does organize the objects and functions, it increases collisions chances.