12 ms·
Some obscure C features
- webkike 9y agoI love taking the address of labels. Back in highschool I wrote a couple of articles on using them to create JIT compilers: http://maplant.com/jit_bf.html http://maplant.com/jit_bf.html http://dginasa.blogspot.com/2012/05/jit-compilation-without-much-assembler.html?m=1 http://dginasa.blogspot.com/2012/05/jit-compilation-without-...
- jessaustin 9y agoThat shorter URL is 404ing.
- webkike 9y agoOops, looks like I forgot to migrate it from my old blogspot
- coliveira 9y agoThis is similar to the technique used to implement gforth. The interpreter is all contained in one function, and the instructions are accessed using local labels and goto.
- loeg 9y agoI believe CPython does something similar.
- cryptonector 9y agoAnd local functions. And __cleanup. And statement-expressions. And Blocks is nice too. All of this should be standardized.
- dmm 9y agoGoogle Cache: https://webcache.googleusercontent.com/search?q=cache:XqXHF0raAVEJ:https://mort.coffee/home/obscure-c-features/+&cd=1&hl=en&ct=clnk&gl=us https://webcache.googleusercontent.com/search?q=cache:XqXHF0...
- WalterBright 9y agoMy not-so-humble-opinion is that if you find yourself doing metaprogramming with the C preprocessor, it's time to upgrade to a more powerful language.
- jstimpfle 9y agoMy take: rethink the problem and the solution. While there are perfect applications of the preprocessor (such as pasting or stringifying tokens) - yes at some point (rather sooner than later) it gets unmaintainable. But I don't share the sentiment that C wasn't powerful. It has everything one needs (and, due to memory control and cpp, arguably more than most languages). These days I mostly use C, and occasionally resort to python as an accompanying scripting language to generate data definitions (either in plain text formats or as C structures).
- vardump 9y agoSometimes you just don't have other options than C. Like kernel drivers, embedded (microcontroller) development. Or perhaps you just need to develop a small loadable library without any runtime (no malloc, etc.). Or perhaps writing Python, Lua etc. C-module for better performance. You just need to treat C with proper respect, not be too arrogant about your skills. I hope over time we can move more and more to Rust or some other language which gives as many errors at compile time as possible and helps with not shooting at our feet. Shouldn't have too many C-macros, of course. Some macro messes I've seen can be nearly impossible to debug...
- pcwalton 9y ago> You just need to treat C with proper respect, not be too arrogant about your skills. We've been hearing "C isn't the problem, bad programmers are the problem" for 40 years. This has continued to perpetuate the problems with the language. I mean, I certainly agree that there are no alternatives to C now for certain domains, but there are real problems with it that aren't solved by just "treating it with proper respect".
- vardump 9y ago
- dfox 9y agoInstead of the tricks with __COUNTER__ it is better to define the macro such that it also defines initializer function which registers whatever you want to register dynamically on program startup. The way of doing that is somewhat non-portable but essentially every interesting compiler-platform combination has straightforward way to do that as it is needed for both C++ (to call constructors of global variables) and ObjectiveC (as part of the code that @implementation expands into) implementations. Edit: also, syntax-wise it seems to me that it is better do define the macro such that it can be used as define_foo(blabla...){ ... code ...} In this case this would involve code like #define define_foo(name, ...) \ static foo_ ## name(); \ ... initializer function ... static foo_ ## name() which also solves the first problem mentioned in the article.
- Gibbon1 9y agoI suppose you could do a linked list hack of sorts to. Just create a linked list of goto labels. When done iterate through to clean up everything. Personal wish for an extension to c is to be able to create a list function arguments and slop that around until needed. int BarBaz(int bar, int baz) { return bar+baz; } auto foo = args_of(BarBaz(10, 20)); ... ... printf( "BarBaz = %i\n", BarBaz(foo)};
- mort96 9y agoI agree with your point about syntax; it would have been nice if the syntax was `define(blah) { ... }` and `it("whatever") { ... }`. However, I don't think that's possible, because I need to include code after the end of the block. That might not be obvious from the simplified macros I used in my example, but it's pretty clear by looking at the actual definitions. The describe and subdesc-macros (https://github.com/mortie/snow/blob/a9ad850df456f78bcf96e1aaeb5f42081f243f63/snow/snow.h#L377 https://github.com/mortie/snow/blob/a9ad850df456f78bcf96e1aa...) need to increment counters and print their status after the block, and the `it` macro (https://github.com/mortie/snow/blob/a9ad850df456f78bcf96e1aaeb5f42081f243f63/snow/snow.h#L336 https://github.com/mortie/snow/blob/a9ad850df456f78bcf96e1aa...) needs to run deferred expressions. I think it would be possible to implement the `describe` macro such that it can be used as `describe(blah) { ... }`, because that defines a function and we can both give the function argument and expect return values from it, but I can't think of any way to do it with the other macros which just create regular `do { ... } while(0)` blocks. If I'm wrong, please show me how; the `foo(blah) { ... }` syntax would make the __LINE__ macro work, it would play better with auto indenters and syntax highlighters, and it would give prettier error messages if you have a syntax error in a test case. I just can't see any way it would be possible.
- d33 9y ago> I don't know how that works, but the important part is that it does. Coding in C is already super risky, as proven by the huge number of projects that have exploitable memory errors in there. Adding complexity using features one doesn't really understand is at best going to complicate debugging and make thing work magically and in the worse case, lead to the risk that someone is actually going to understand how your code works and exploit it. Not worth it.
- loeg 9y agoIt's just a "computed goto." A GCC extension, yes, but not a particularly hard one to understand.
- gkya 9y agoThe author is talking about code used in a unit testing library that he is developing. As long as you don't release your test code as part of your software package, I don't see why some smart shortcuts that can help with the programming experience can not be used.
- mort96 9y agoI might not have expressed myself clearly enough. It's not risky, it's not a feature I don't understand how it works, and I'm using it exactly as it's described in GNU's documentation on labels as values and computed gotos: https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html The "I don't know how that works, but the important part is that it does." sentence was meant to highlight the apparent absurdity of dereferencing a void*, not to say that I don't understand exactly how to use the feature.
- cperciva 9y agoOnly the first two of these are available in C. Computed gotos and local labels are gcc extensions; and the dynamic linker is POSIX but not C. (Incidentally, the dynamic linker hack is precisely how both FreeBSD and Linux perform all their kernel initialization: Individual modules define symbols with a particular naming pattern, and then the kernel linker enumerates those symbols.)
- mort96 9y agoThe second sentence in the article: > I wanted to see how close I could come to making a DSL (domain specific language) with its own syntax and features, using only the C preprocessor and more obscure C features and GNU extensions.
- cperciva 9y agoI was objecting to the misleading title (which is currently "Some obscure C features"), not to the content of the article.
- loeg 9y agoI think you're missing the point of the article. The author isn't limited to standard C, and neither is anyone with a unix and GCC. Are you just nitpicking the author's description of extensions as "C?"
- sammoorhouse 9y agoI find that some HN people read articles with the express intention of picking nits. Like the dwarf with learning difficulties, it’s not big and it’s not clever.
- kbenson 9y agoIt was a clarifying comment, didn't denigrate anyone, and added a useful and interesting tidbit of information. I see nothing wrong with this. Perhaps the comment author should receive some benefit of a doubt as to his intentions?
- varjag 9y agoInteresting as highlights of what C preprocessor and compiler extensions can do. But I'd hate seeing it in actual production code.
- WalterBright 9y agoI used to be enamored with what I could do with the preprocessor back in the 80's. I've since reverted all of that (in C code I still use) back to mundane uses of the preprocessor. Eventually one tires of no support in the symbolic debugger, program analysis tools, compiler error messages that are based on the post-expansion code, nobody else understands the code, hygiene problems, etc.
- varjag 9y agoExactly my sentiment, especially the collaboration part. If you take it too far, you effectively invent a new language. Forcing it upon others is more about hubris than skills.
- MaxBarraclough 9y ago> you effectively invent a new language Perfect. Can't tell if that's deliberate.
- cryptonector 9y agoDo you use PuTTY? Because PuTTY does crazy C macro things. Actually, maybe not that crazy. It just has C functions that a thousands of lines long, using macros to turn them into fancy Duff's device co-routines.
- varjag 9y agoNo I don't use PuTTY. Also, I'm aware what you can do with C macros, doesn't mean you should do it. See my sister comment.
- murftown 9y ago
- epilk 9y agoI also encountered the last problem, it can be handled pretty easily with __attribute__((constructor)): void (*_test_functions[NTEST_FUNCTIONS])(void); int _test_function_idx; #define TEST_FUNCTION(fname) \ void fname(void); \ __attribute__((constructor)) static void _init_ ## fname (void) { \ _test_functions[_test_functions_idx++] = fname; \ } \ void fname() TEST_FUNCTION(test_foo_bar) { assert(foo_bar == 0); }
- apaprocki 9y agoA quite fun, related feature of the AIX linker, is that it will automatically make any function name prefixed with "__sinit_" statically invoked the same as this attribute does. So you name the function a certain way to take care of AIX/xlc, add pragmas to take care of other UNIX vendor compilers add the attribute for any GCC-based (or compatible) compiler, and they are actually pretty cross-platform! Not... that... I would use these all the time or anything like that :)
- pjmlp 9y agoThe fun was even better in the old days, where each UNIX had a different concept of what a shared object should be. AIX used to implement shared objects just like on Windows, using an export definitions file and import libraries, for example.
- apaprocki 9y agoStill does to this day. And it has a machine-wide cache of libraries, so simply updating the library and restarting the processes isn't enough to get the new version -- you have to be aware it could be in the cache and might need to be manually flushed by someone with elevated access. shudder
- pjmlp 9y agoThanks for the clarification. Last time I used it was about 2003.
- jstimpfle 9y agoSending blocks as arguments to macros: Just wrap them in another set of parentheses. For parentheses-balanced input (such as valid C blocks) this should always work (I think). $ echo '#define x(a,b,c) a b x(1, (2, 3), 5)' | cpp
- mort96 9y agoThat isn't really a viable solution, because C doesn't allow parentheses around blocks. Calling `describe(foo, ({ int a, b; }))` would make the preprocessor happy, but it would also produce invalid syntax: void test_foo() ({ int a, b; })
- cryptonector 9y agoTsk tsk, if you're going to know about label values and other GCC C extensions, you might as well know about statement expressions (another GCC C extension). `({ <statements> })` is an expression. Naturally, Clang also supports statement expressions... EDIT: I highly recommend spending some time reading about all the various GCC C extensions, and what compilers support them (typically Clang, but also Sun Studio, if that's still around..., and maybe others). There are quite a few very useful ones.
- loeg 9y ago@mort96, for the latter example, the BSDs provide this in the sys/linker_set.h header, with macros like SET_BEGIN, SET_FOREACH, etc. Unfortunately I don't see the same functionality in Linux headers, but there's no reason the same technique cannot be used there.
- mrgriffin 9y agoThe author tried using __COUNTER__ and a static array of function pointers, and narrowly missed a workable idea—a static linked list! Forward declarations pun definitions, and can be used roughly as follows: struct Element { int value; struct Element *next; } #define ELEMENT(value) _ELEMENT(value, __COUNTER__) #define _ELEMENT(value, n) \ struct Element CAT(e, SUCC(n)); \ struct Element CAT(e, n) = { (value), &CAT(e, SUCC(n)) } You can then walk from e0 through the linked list, but because of how the initialization works, you're done when the current element has `next == 0`. int main(void) { struct Element *e = &e0; while (e->next) { printf("%d\n", e->value); e = e->next; } } Here's a repl.it: https://repl.it/repls/DetailedYoungAsianconstablebutterfly https://repl.it/repls/DetailedYoungAsianconstablebutterfly
- mort96 9y agoThat'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__.
- Animats 9y agoOr, "Things you can do with macros in C, but probably shouldn't."
- cryptonector 9y agoWhy not? I'm serious. Please don't say "don't use C". We all agree on that. I'm asking why one should not use clever macro tricks -- I know many codebases that do, and I'd not shy away from it when I have to use C anyways.
- kbwt 9y ago> Please don't say "don't use C". We all agree on that. I wouldn't be so sure John Nagle agrees with such a blanket statement.
- ggm 9y agoEnormously powerful, and powerfully unreadable for mere mortals. you can take the assembler out of the loop but you can't take the failure to comprehend out of the programmer. I don't do C for a living any more (barely did) but the number of times I asked smarter people "why did you use this idiom with this terrificly confusing side-effect" and they said "thats not a side effect" comes to mind...
- 0xcde4c3db 9y agoMy favorite (somewhat) obscure C feature: puts("Line one\nLine two\nLine three"); and puts("Line one\n" "Line two\n" "Line three\n"); mean the exact same thing. This can be a godsend for making complex debug/log output more presentable in the source.
- rxaxm 9y agoin college my buddy made a defer function in C that is a little simpler (but only works with clang) https://github.com/asubiotto/cdefer/blob/master/defer.h https://github.com/asubiotto/cdefer/blob/master/defer.h
- cryptonector 9y agoIt's not just that it only works with Clang, but that it only works with Blocks (Apple's extension to C which basically adds closures of indefinite extent, which is pretty cool).
- faragon 9y agoMore examples (C89/90 preprocessor compatible): Function building using templates: https://github.com/faragon/libsrt/blob/master/src/saux/ssort.c Passing macros to macros (meta-templates): https://github.com/faragon/libsrt/blob/master/src/saux/ssearch.c
- ziotom78 9y agoReally interesting read. However, I fear that if other C library maintainers will start to use this kind of techniques, creating bindings for other languages will become increasingly difficult.