340 points · by mort96 · 8y ago · 156 comments
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/DetailedYoungAsianconstablebutterflyThe linker's job is to combine all the separate pieces in a "section" (special linker term) and write out one section.
Using a special named section lets you create an array using macros, though using it for function pointers is probably safe and using it for other data types might be pretty fragile. http://www.compsoc.man.ac.uk/~moz/kernelnewbies/documents/in...
Turned out the macros I overlooked at the end of each file placed the struct defining the command in a special linker section, and the parser init would go and load all the commands from that section.
Interesting to know that this trick already existed in the Linux kernel.
I'm (perhaps perversely) disappointed we aren't using more of the linker's power in many C codebases.
This is the reason why I do not like such tricks. This obviously hurts maintainability and probably portability. Is the tradeoff really worth it? Plain stupid registration is just a single line. KISS.
"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" –Brian Kernighan
A primary problem with linker magic is that it is usually very non-portable. Hacks you do with macros may be ugly but at least they work everywhere, unless you used a non-standard behavior.
Linker tricks tend to be platform specific, and even more so that other tricks (eg POSIX platforms share a lot of common behavior, but still tend to have quite different linkers).
https://msdn.microsoft.com/en-us/library/bb918180.aspx
Another interesting thing is that it relies on the linker ordering names in alphabetical order.
// COUNTER.h
#if !defined(COUNTER)
#define COUNTER 0
#elif COUNTER == 0
#undef COUNTER
#define COUNTER 1
#elif COUNTER == 1
#undef COUNTER
#define COUNTER 2
...
#end if
And then change each invocation of ELEMENT to have a leading #include "COUNTER". #include "COUNTER.h"
ELEMENT(x)
#include "COUNTER.h"
ELEMENT(y)
Note that if you take this approach then (as far as I know) you're actually writing standard C!> 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).
__attribute__((constructor))
https://github.com/kbob/schetoo/blob/master/prim.h#L215
This also works across multiple source files, unlike __COUNTER__.
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.
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...
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".
But often you just need to get the job done, and have limited options available.
Perhaps in 50-100 years, people looking back at software from this era won't be able to understand how we managed to make it work at all.
I haven't met or know anyone mastering C/C++ (especially C++), and doubt I'll ever hear about one.
This is true. With all the new and fancy languages around, it's strange that there are so few attempts at making a better C.
I would say that the characteristics of C is: dead simple, manual memory management, "fancy assembly".
Rust is close, but fails on being dead simple.
The best attempt I know of, is Zig: http://ziglang.org/
But it's still very early in development. I am using it for microcontroller code right now though, and it's much nicer than C already, despite having to deal with bugs.
You always have other options if better languages can compile to C or integrate it via FFI. There's been plenty to do that, too. For simple and safe, Modula-2 was early one compiled to C that couldve had syntax modified to be more like it. If aiming for power, PreScheme was a systems dialect of Scheme that compiled to C at one point. The OcaPIC (Ocaml) project and use of ATS language for 8-bit show stuff like that could probably be made to wofk in areas C is used in, too.
So, I'd say it's a myth you need to develop in C just because a target has only C libraries or compilers that safer languages can use. Instead, we get a new claim that people just didnt do it for reasons that varied per project or person but wasn't technical capability.
Use Common Lisp to generate C code. There are three libs that are specific for this, see C-mera for example.
Is this a joke, or do they do some sort of stack-bounding static analysis?
My guess is that in most (not all) cases C++ is usable instead of C, but the culture of such development is to prefer C. It's a real pity, because for someone with a moderate amount of judgement (i.e. not going off the deep end on unnecessarily complicated C++), it only takes a moderate amount of C++ knowledge to be able to write more maintainable and correct code that performs equally well.
For example, to produce generic SIMD-accelerated code over both Intel-specific SIMD operations and the Sleef vector math library I needed for FHT-based JL-transforms and kernel projections, I used template specialization to abstract to operations on physical memory. [0]
The generic methods themselves were gross, but in application, it was extremely simple in downstream code to specify an operation and a container and have the compiler pick the fastest method for the job. I’ve also checked my generated assembly and the smaller functions are always inlined, even though they’re called from static constexpr function pointers.
This is also a great use case for macros, as they saved me huge amounts of typing.
I’m sure many will say C++ is the wrong direction to go for metaprogramming, but it’s worked great for my purposes and lets me get straight to the hardware.
[0]: https://github.com/dnbaker/frp/blob/master/include/frp/vec.h
Python has incredible productivity and versatility with ease of learning. It's readable. It's easier to prototype things like verification tools in it than C. There's also tools like Hypothesis to test that. Then, there's tools to speed up the code like Cython.
If anything, Python would be a safer, faster way to write tooling for modifying or testing C code than C itself. One could also convert Python generated tests to a C library of tests with automatic validation of data types, coverage, etc. So, I think it would make sense if someone did anything from prototyping C in Python to using it to test C code.
And do note Ive enjoyed reading your experimentation with macros in C. I learned about defer through it. Just commenting on that one point.
I think this is because writing python code is like writing C++ without templates, but all the integer types declared “auto” and all the pointers void.
The main difference is that the C++ compiler
still* does more type checking than python even after you abuse the warning flags enough to get it to stop gently telling you to change professions!)Reading it reminds me of when I accidentally got my emacs syntax highlighting stuck at “white on white” for a bunch of stuff, but I digress.
I guess I find it to be a completely unproductive, unreadable, and unmaintainable language. It’s OK for throw away prototypes, but I’ve never seen a team throw away a python prototype and rewrite it in another language. I know of python projects that failed and were [repeatedly] rewritten by the same team in python, and I know of python teams that failed and got swapped out for another language, but that doesn’t count. Part of the problem with the python prototyping story is that python wants to own the event loop and asynchrony / thread model, and changing those are often the main reason to swap languages — the next step is always a rewrite in my experience.
Wow. Long rant. One too many ‘assert “” != None’ errors this week. :-)
TLDR: because you need to test the real thing, and using Python to test C code causes too many important differences between tests and production.
To test C code you need to compile it, and there’s no C compiler inside Python. Also if you have C++, sometimes you can abuse templates for similar effects, and Python doesn’t have C++ AST either.
C toolchains largely depend on environment: included & linked files, environment variables, compiler & linker switches, they all make a huge difference. You’ll spend much time replicating that in Python, and it’ll break when you’ll upgrade any part of toolchain (compiler/IDE/build automation/etc).
To a lesser extent, same applies to native binaries as well. If you’ll manage to use Python to produce tests, C compiler to build them, then Python to run them — the runtime environment will be different from the real one.
I have been working on Snow, a unit testing library for C.
OP requires a unit testing library for C, so they've written one. What is the alternative solution you propose? The framework itself may appear complex, but the entire end goal here is to provide simple/abstract tools to write tests in a readable/self-documenting manner. The framework itself is the mean, not the end goal.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).
Macro metaprogramming is still needed in C++. Other powerful languages might lack some nice properties of C. Like easy interfacing with other languages, and a wide availability.
(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.)
> 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.
Are you just nitpicking the author's description of extensions as "C?"
Perhaps the comment author should receive some benefit of a doubt as to his intentions?
Yes, it doesn't denigrate anyone, but that's a really low bar.
I do give authors the benefit of the doubt when something isn't clear. That's why I couched my message in "I think" and asked a question instead of just asserting facts.
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);
}AIX used to implement shared objects just like on Windows, using an export definitions file and import libraries, for example.
http://maplant.com/jit_bf.html
http://dginasa.blogspot.com/2012/05/jit-compilation-without-...
And __cleanup.
And statement-expressions.
And Blocks is nice too.
All of this should be standardized.
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.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/a9ad850df456f78bcf96e1aa...) need to increment counters and print their status after the block, and the `it` macro (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.
#include <stdio.h>
#define before_after(before, after) \
for(int before_after_##__LINE__ = 0; \
before_after_##__LINE__ < 3; \
before_after_##__LINE__++) \
if(before_after_##__LINE__ == 0) { \
printf("%s\n", before); \
} else if(before_after_##__LINE__ == 2) { \
printf("%s\n", after); \
} else
int
main(void) {
before_after("hello", "world") {
printf("to all the\n");
}
return(0);
}Your snippet won't work with this inline example:
before_after("hello", "world") { before_after("hello", "world") { }}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)};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...
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 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.I wouldn't be so sure John Nagle agrees with such a blanket statement.
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.
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.
$ echo '#define x(a,b,c) a b
x(1, (2, 3), 5)' | cppCalling `describe(foo, ({ int a, b; }))` would make the preprocessor happy, but it would also produce invalid syntax:
void test_foo() ({ int a, b; })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.
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.
Perfect. Can't tell if that's deliberate.
PostgreSQL source code for example, has a foreach() macro that loops thru a linked list.
At the same time the abstractions provided by C preprocessor are too weak for significant productivity gain via elaborate DSL route.
It's better to rather stick to universally understood vocabulary than force your sometimes buggy, often inflexible language upon others.
That being said, C Preprocessor behavior is pretty simple once you know it, and modern compilers are pretty good these days about helping you see what happens when you have an error in your macro-expanded code. You're right though, good to stick to the universally understood vocabulary.