namespace constants in C

Saw this on mikeash’s Twitter. Namespace constants in C.

#import <Foundation/Foundation.h>

// .h file
struct MyConstantsStruct
{
    NSString *foo;
    NSString *bar;
    int baz;
};

extern const struct MyConstantsStruct MyConstants;

// .m file
const struct MyConstantsStruct MyConstants = {
    .foo = @"foo",
    .bar = @"bar",
    .baz = 42
};

// user
int main(int argc, char **argv)
{
    [NSAutoreleasePool new];
    
    NSLog(@"%@ %@ %d", MyConstants.foo, MyConstants.bar, MyConstants.baz);
}

So obvious once you see it… why did it take us this long to think about it? 🙂

4 thoughts on “namespace constants in C

  1. Ever since I started programming in C, I’ve gotten into the habit of putting my global variables into a struct called _, so using _.myvar instantly shows it’s global. Or the pointer to the struct would be called _, so _->myvar.

    In fact, when I did embedded 68K programming, the _ struct could be defined in the lowest 32K, to get faster and shorter access – the compiler would emit 16-bit addresses.

    The code _does_ tend to look a little bit odd… 🙂

    • Why isn’t this promoted more? I mean, all these years and it’s just dawning on a bunch of us… tho obviously, you were ahead of your time. 🙂

      It might look odd, but there’s a lot of good in it.

  2. This is awesome. I thought.
    Too bad ARC forbids pointers to Objective-C objects in Structs… booh.
    It is still possible to create enum lists and then

Comments are closed.