Re:Some obscure C features
by mort96 on Thursday January 25, 2018 @06:21PM
(#16235707)
That's really neat, I hadn't considered that. I will definitely try it out, and might end up using it for the library.
[ Parent
| on HN ]
I think the other solutions proposed are better, but:
> Sadly, you can't set the value of an index in an array like that in the top level in C, only inside functions.
This is not exactly true. An assignment is a value, you can do e.g.
int a = b[x] = 0;
(which implies that you can do your array-index assignments at the global level by creating nonsensical/unused variables and initializing them).
There's a simple solution you're missing here:
__attribute__((constructor))
This is what I came to say. Here is a working example that builds an array of function pointers at program initialization time.
https://github.com/kbob/schetoo/blob/master/prim.h#L215
This also works across multiple source files, unlike __COUNTER__.
Yeah, it's a weird one! I discovered the idea while building my own toy unit test library, but I never got around to finishing it.
The biggest downside is that (as far as I know) it's impossible to get this approach to coordinate across translation units, so you're forced to define a main in each test file (via the library's header file?). But I doubt that matters too much in practice.