5 ms·
That's really neat, I hadn't considered that. I will definitely try it out, and might end up using it for the library.
by mort96 9y ago
That's really neat, I hadn't considered that. I will definitely try it out, and might end up using it for the library.
- mrgriffin 9y agoYeah, 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.
- nialv7 9y agoThere's a simple solution you're missing here: __attribute__((constructor))
- kbob 9y agoThis 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 https://github.com/kbob/schetoo/blob/master/prim.h#L215 This also works across multiple source files, unlike __COUNTER__.
- vpalanc1 9y agoI 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).