Disadvantage of using a struct as a c "namespace"

347 Views Asked by At

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

2

There are 2 best solutions below

0
On

Disadvantage of using a struct as a c “namespace”

Increase collision potential.

The idea here is to use foo.a, foo.x and foo.bar() vs. maybe foo_a, foo_x, foo_bar(). The trouble is now foo collides with any other 3 character foo 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.

1
On

More memory is allocated because of structure alignment (more info here). A struct instance will have the alignment of its widest scalar member.