111 points · by susam · 3y ago · 218 comments
Obviously there is C++ which can leverage most of this too, but C++ traps you into an ABI which is difficult to use from any language which is not C++.
With that said: Swift replaced C (and Obj-C) 100% in the Apple world for me. Because the API bindings are as good.
C's "register" keyword has been ignored since 1990 or so.
Does D support anything like `__attribute__((section("t1")))`, so we can have the linker decide how to locate some compiled code, or computed gotos?
Can we use D's inline assembler to clobber registers?
I've had trouble even with clang and extended asm. For example, LLVM does not support the "g" constraint.
I understand that there aren't many use-cases for these specific features, but I have an unusual direct-threaded VM which relies on some of them, and the only real alternative I see is to write plain assembly.
And of course LDC supports all the LLVM custom attributes, plus GCC-compatible inline assembler (not sure about the "g" constraint though) and LLVM-style inline assembler.
D's inline assembler does register management for you, i.e. it tracks register usage through the instructions, so you don't have to say which registers are read or written to.
D does not support the "section" extension. I understand that certain gcc C extensions are needed for special purposes. Gcc may be the most suitable language if you need those extensions.
What I would do is use gcc for the parts of the code that need those extensions, and D for the rest (D code can directly interact with C code).
I found this pdf but I thought there was a different one, anyone link to that?
To be fair to C++, all the other languages in this space are as bad at providing ABIs in their own languages. All (almost?) mostly provide ways to declare C ABIs, which C++ also supports.
C++ has rough C++ ABIs, but mostly because it bothers to try in the first place. It's not like other languages really "solved" ABI better than C++ has.
Even C ABIs are a little rough since there's so much preprocessor use to factor in and/or avoid.
This is why it's pretty standard to just have a C FFI and provide a C wrapper for C++ libraries to use them with other languages.
But for example, the Rust ABI uses the C++ ABI, because C is too simple and doesn't support unwinding (for panics) or 128bit integers
I just wish their trademark policy relaxed some of the non-trademark related requirements making it a deal-breaker.
Btw the recent fuzz recently was about some proposal and not the actual one. This is the policy: https://foundation.rust-lang.org/policies/logo-policy-and-me... and I don't see any deal breaker.
Which language is?
I mean, if you're going to parrot this line, surely you have an example of a language that is more closely aligned to hardware than C, right?
I see this line repeated in every HN thread about C. It's not a new sentiment, but it is mostly wrong because the implication is that there exists some other popular language that actually aligns with the hardware better than C does.
https://wiki.osdev.org/System_V_ABI
The System V ABI is closer to being a standard than some official standards are.
C++ gets odd with name mangling, but the platform's C ABI is typically the tune every other language must dance to for its FFI.
That brings back some unpleasant memories. What happens when a popular compiler decides that whatever they choose is the ABI, and the published spec be damned? https://gcc.gnu.org/bugzilla/show_bug.cgi?id=38496
https://en.wikipedia.org/wiki/IBM_i
https://os.mbed.com/docs/mbed-os/v6.16/apis/platform.html
Not every OS is written in C, thus the platform ABI isn't always C.
While Alef failed, Limbo's design with GC was considered a revisit from what was missing from Alef.
They also miss that lint was considered a must have tool for safer C code, introduced in 1979, and that Dennis actually proposed fat pointers to ISO, which weren't accepted.
https://en.wikipedia.org/wiki/Alef_(programming_language)
http://doc.cat-v.org/plan_9/2nd_edition/papers/alef/
http://doc.cat-v.org/inferno/4th_edition/limbo_language/
And which of these three operating systems won?
Compared to Plan 9, Unix creaks and clanks and has obvious rust spots, but it gets the job done well enough to hold its position.
There is a lesson here for ambitious system architects: the most dangerous enemy of a better solution is an existing codebase that is just good enough."
Source: https://www.catb.org/esr/writings/taoup/html/plan9.html
Implicit conversions are one thing I don't like about C, or at least the way it ended up as int grew (maybe it would have been better if ANSI had picked unsigned-preserving, but maybe that's just grass-is-greener thinking). I also don't like how UB turned into “a license for the compiler to undertake aggressive optimizations that are completely legal by the committee's rules, but make hash of apparently safe programs.”
I do like the directness and explicitness. Good C can be very nice.
You can have a language where all the behaviour is defined but in my experience most programmers who whine about this in C are just as unhappy because what they actually wanted was DWIM. In a language with defined behaviour their program is wrong, which is their fault, whereas in C they can claim "obviously" it's the compiler's fault.
I like it when it's my fault, I just learned something, and early in my education I assumed everybody was the same but I rapidly learned that most people prefer to be told they're correct regardless, and a language which says "Nope, 4 - 5 is a negative value and this variable in unsigned, too bad" makes those people unhappy, whereas when 4 - 5 = mysterious program behaviour they can blame the compiler engineers instead.
assigning -1 to an unsigned variable has never been undefined behavior either, but implementation-defined behavior (see §6.2.1.2p3 in iso c90 or §6.3.1.3 in c99 and c11); decent compilers like gcc define it to do the obviously correct thing (see https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.h...), not produce mysterious program behavior. in the new c++20 standard it's no longer even implementation-defined, but fully define behavior in the standard, but in standard c it's still implementation-defined
as a programmer who whines about the kind of ub exploitation at issue here, and who (as established above) has a much clearer idea than you do of what behavior is and is not defined, specifically what i am whining about is that it's harder to debug my code if doing things like dereferencing a null pointer doesn't reliably crash it, but instead triggers the silent removal of apparently unrelated logic from my program, or subtle semantics changes in it, in the name of optimization
also it sucks to have existing security-sensitive code acquire new security holes, and i don't really care if that's a learning opportunity for the guy who wrote it 20 years ago
this didn't happen 20 or 30 years ago, and in those 20 or 30 years the impact of introducing fresh security holes into existing well-tested c code has greatly increased, while the usefulness of c compiler optimizations has greatly decreased
If you give up the aggressive optimisations then C is even less competitive with modern languages, so you're basically arguing that it's acceptable to have code that's harder to write, more buggy and with worse performance just because that's how you'd have done it 30 years ago. At that point you're talking about a retro hobby.
stop trying to coerce me
But:
> My perception of the second sort of C programmer is that if they've moved to any more recent mainstream language, it's probably Rust.
If in this context the "second sort" is the type who likes C on its own merits (rather than because they don't have any other choice), I think Zig is a much better option than Rust.
The author asserting the second sort would have moved on to Rust makes sense. They are ones who are trying to get away from C ideas
- there doesn't have to be "two kinds". Trivially you can fit both "types" at once, I certainly feel that way. And if there are 100 programmers, there'd be about 237 other reasons to use a language. False dichotomy.
- a better categorization might be "there are two kinds of C programmers: those who eventually start using rust and those that don't." which is at least of course absolutely true.
- I dislike the idea that a programmer is bound to a language. He's a "C" programmer, She's a LISP person, etc. A good software engineer should use about 5-10 different languages appropriate for the purpose at hand.
Sure it seems so when you start. K&R and away you go, that programming is a lot easier than writing rust sure.
But unless you are writing for just yourself, no current C software get developed that way. You need to understand C standard, that is quite complex and you need to understand it in detail because of undefined behavior (and of course how your compiler interprets it and sometimes fight with compiler to emit right code).
Then you needed to know all the gotchas in the standard library, and how you properly use them. Then you need to know how to do basic arithmetic without having undefined behavior (that's where a lot of memory leaks happen). Or maybe the software you are working on has created their own implementation of most of those functions, so you need to figure how to use those. Even to just print out a debug statement can sometimes be nontrivial.
And of course you need a way to compile the damn thing, just figuring out what sane options you need to use to get decent warnings and what they mean takes a while.
And when you figure all of that out, you still need to keep track of most of the stuff that borrow checker does, but this time by hand using comments and conventions (that you also need to learn for each project.)
(I left out whole build setup, but its usually harder than Rust one too. )
I believe that programmer who has only programmed java or maybe C# before (or python, js...) will get up too up to speed faster on Rust than on C on most real-world projects
C is deceptively simpler.
With Rust, you have to think very differently about how to e.g. structure your data to make the borrow checker happy in many cases. This doesn't really translate to anything similar in other mainstream languages; it's a whole new skill that has to be learned.
Nothing in the article suggests that being a "C programmer" is that kind of a binding label. It's you reading that into it ;). (Though certainly influenced by the fact that that is a widespread interpretation.)
FWIW, I consider myself a C programmer, and in both camps presented in that article. But I'm also a Python programmer, and I don't think either of those two languages "owns" me.
But many of my side projects are Java and she is always first in my heart no matter where the money takes me.
If you are the first type, you likely get the second type’s taste wrong. Rust is very very different from C both in terms of syntax and philosophy.
I know many people see "complex with angle brackets" and equate Rust more with C++, but I disagree and think it's still closer to C — I can convert C libraries 1:1 to Rust, but C++ libraries hit an impedance mismatch and are really hard to rustify.
Things have a drop-scope. There are hidden initializations. Boxing is required for many things including dynamic dispatch in error handling. The tendency to use FP-like one-liners. All that mixed with funny syntax that hurts C developers eyes.
A lot of "no-go" in C land (at least for me), that makes really hard to learn and to move definitely into Rust (again, at least for me)
That said, like the author, I'm trying to find an alternative. Well, more like I'm building my alternative because I hate Go. And Rust. And anything else.
I don't know why C fits my brain, but it does. I think it's because my brain is low-level; I like messing with assembler when I get the chance to optimize.
[1]: https://gavinhoward.com/2023/02/why-i-use-c-when-i-believe-i...
You cheat. You don't write C the hard way. But ok, that's an easier way to use C today.
I'm okay with cheating if it reduces bugs.
It's all in a monorepo that has my "libc".
this is not a controversial statement, it's the clear conclusion from any evaluation of available evidence
it's fine that you like messing with assembler, but you can't do that safely -- if the programs you write don't need to be correct then carry on, but if they do need to be correct, then you have a professional obligation to use a higher-level language, with stronger guarantees
edit:
> This brings me to my next reason: I have the discipline to write C at a high level.
factually, you do not. nobody does. you think you do, until you don't. human cognition is insufficient to satisfy this requirement. "discipline" does not fix the problem.
I don't disagree [1], but remember that Rust can be unsafe too. Async is not a panacea, and it's confusing. And the `unsafe` escape hatch is still unsafe.
> you have a professional obligation to use a higher-level language, with stronger guarantees
Oh? So we have professional obligations now? For FOSS? News to me.
I don't get paid for my work. Not yet. So I have no obligation.
And when I do get paid, my code will be in my own safe language.
This accusatory response is exactly the kind of thing that puts a lot of people off Rust.
> factually, you do not. nobody does.
When I say "write C at a high level," I don't mean that I'm perfect. I mean that I write excellent C compared to all C programmers out there.
Engineering is not about perfection; it never was. It's about doing the best we can with the tools that we have.
[1]: https://git.gavinhoward.com/gavin/bc/src/branch/master/MEMOR...
All code is machine code at bottom. Including the code that maintains abstractions convincing enough for you to think the “memory-safety” of rust or any other language is a static and guaranteed thing and not something that needs “unsafe” scaffolding to support it.
Much of the Rust compiler is written in Rust and so has fewer problems.
It's not possible for human beings to write correct code.
The hardest bug I ever found in a C program, one that took cumulative weeks of work until a tractable reproduction was found, came down to a ‘<’ that should have been ‘<=’. No language would have stopped that.
Yes, different languages have different levels of expressiveness, and can preclude or expose different kinds of errors. You'll never have a stray pointer in Python, and you'll never OOM making an accidental copy in C.
In that case this could have been caught with more careful unit tests, which would have exercised the erroneous condition, and potentially with fuzzing to excite corner cases. C is... not great for either of these.
yet c code is inarguably more error-prone than basically any other language
It's true that the community at large writes lots of bugs. But that doesn't mean some people aren't productive with the language and write a relatively low number of bugs. There are some projects with better track records at this than others.
at scale, it is not possible for humans to hand-write C programs that are free of segmentation fault class errors
this is not controversial or in any way arguable
In early 1980's it was only running Bell Lab's world and a couple of universities that got hold of the source tapes.
"it works" is factually not true, look at ~any CVE
I agree that C the programming language does not help you avoid memory errors, however, saying it's impossible is too binary. People do make mistakes, whether it's copy editors missing a typo or professional chefs misremembering whether they stocked an ingredient. Projects written in C need longer periods of code review and testing, but they can be made right. The code that took us to the moon was written in assembly after all.
I think primarily about the kind of machine code I want to generate, and pick a language that best approximates that ideal output code while still allowing the source code to be as clear as possible.
From these constraints I keep coming back to C. Zig is the most appealing contender in terms of next-gen languages.
If I could get safety without giving up anything, of course I would take it. But I am increasingly convinced that this is not generally possible.
This is one of the things that endears me to Zig: passing an explicit allocator around is a very common idiom in the language.
The scripting langues are great for high productivity and mediocre performance. Shell languages are great for interacting with the operating system. Query languages are great for interacting with big data. But for years, C was the unparalleled language for getting the best performance out of CPU-intensive algorithms. I've still never found a language that erases these boundaries -- while I'm a "C programmer" I'm multilingual by necessity.
Today? C's performance is matched by C++, and more tedious to write. Zig is there on performance, but for my purposes, the language gets in the way. Rust also gets in the way, and can end up forcing reference-counting which tanks performance. I do like how Go mostly gets out of the way, but again, I cannot abide unnecessary reference counting.
* and, yes, the abstraction is a lie, but it's an incredibly useful and high-performance abstraction
I guess zig for me is indeed a slightly more complicated language than c, and it's way more verbose, but what I appreciate about it is that straightforward code looks good and code that is on shakier ground looks hairier which is basically a "this code is sus, plz review the fuck out of it" sign.
In the end though, what gets in the way for me with C is everything else to ship a "real c program", especially when you want/need someone else's code. Lexical macros, header/code separation, flat namespace, errno, architecture dependent definitions for int, char, etc, having to think about object (file) units, make, automake, config...
At that point the cognitive burden is enough that a small added complexity in the language is worth it
If you don't mind me asking, how does Zig get in the way? My own gut feel is that it's the only real "better C" out of the present crop of alternatives.
Here’s a web framework (complete with ORM) modeled on ExpressJS written in C:
https://github.com/williamcotton/express-c
The finished product is < 90Mb Docker image that idles at like 2Mb of memory.
There’s also a lot of examples of the (basically required) support tooling like Valgrind, AdSan, etc.
Check it out!
I'd like to share my project as well: a Lisp interpreter written in freestanding C.
I think this has a slight advantage in that it uses a memory arena for a per-request bump allocator so it should keep overall memory usage lower.
The slowest part of all this has to do with Block_copy and the places where I’m very much treating blocks/closures in an OOP type manner.
This could be fixed by writing a different function that did basically the same thing as Block_copy but for all the “methods” on an “object” in a single pass. But who has time for that? :D
Here’s more about those performance issues and some example code that show how slow the approach is:
https://github.com/williamcotton/express-c/tree/master/resea...
but your point is sound, any reasonable go http server will have the same level of memory usage at idle
fine for a toy project, not something that can be used in anger
Yeah, I definitely wouldn’t use that approach for user input! There’s also support for mustache templates and JSON-API endpoints as well.
Or are you referring to something else?
But yes, please don’t use this for anything serious!
In a word, simplicity. A language designed by a single person. I also did program a lot in CLisp, a language designed by committee, with more than 100 different flow control directives(and people often create their own).
I loved and love Lisp as a concept and tool, but hated CLisp complex design so badly. I programmed in Arc for a while because of that.
I have created my own C compiler and interpreter. Something impossible to do for a single person in C++(C++ is way more complicated).
I also love manual memory handling in C because it lets me create my own automatic local systems much more efficient than someone else's "one size fits all" aproach.
I have also programmed mac apps in Objective C and Swift, C++, java, javascript, Perl.
I program today mainly in four languages: C/C++, Python, Rust and Clojure.
With C it is so easy to create python modules. It is trivial to interoperate from C++ with C. Clojure is a Lisp that is simple, clean design, and you could interoperate with java objects. Rust has some advantages over C, but also disadvantages(it is too bloated).
I wrote a fully compliant C++98 compiler (Digital Mars C++).
For fun, go to /usr/include and try to understand the system .h files.
It's relatively simple because everything is UB/UsB/IDB. ;)
In some cases efficient memory management _is_ the problem to be solved. I'm not just talking about esoteric or embedded systems here. If you're developing for modern GPU's with a modern API, like Vulkan, you must manage GPU memory yourself. With direct memory access you can do many "unsafe" things, like memory aliasing, to improve performance. "Safe" languages, like Rust, will not help you here.
I still don't "know" C or what's a customary way of doing things because I only started with C code by Martin Jacob that executes machine code in a memory buffer ( https://gist.github.com/martinjacobd/3ee56f3c7b7ce621034ec3e... ) and some Perl Compatible Regular Expression library example C file.
I want to know C enough that I can create good APIs in it and transpile to C effectively because I want to take advantage of LLVM and gcc optimising backends.
A beginner might want to make a web request, good luck doing anything beyond mimicry with C from code samples if they get that far.
With python, they could pull it off quickly.
This was before C++ was standardized and we had to make do with whatever MSVC 1.5 would do. It did not even support templates back then and even the highly polarizing STL did not exist yet -- in a cross platform way; The STL source itself was available from 1994, and if I recall right, the C++ compiler on Sun/Solaris supported templates etc., We were then a Sun/Solaris + Dell/WinNT shop then and had software running on both and therefore settled on the lowest common denominator of features supported by compilers on both platforms.
Heady days.
Given that environment, I was comfortable switching between C and C++.
MSVC was always behind until Borland management messed up.
But my first job had standardized on MSVC. So, that determined what I used on the job.
Loved Turbo Pascal and Turbo C++ IDEs in those days. Simple and fast!
This is how I feel about assembler. No rules, you on your own. And it is impossible to imagine simpler language. Though I do not write asm lately.
Sometimes differently typed programmers will implicitly agree to adopt a uniform approach before working together on a project. Sometimes the programmers won't do this by themselves and so a manager is needed to explicitly guide them to adopt the appropriate type.
However, some types stubbornly resist conversion, and so are tricky to work with. Pointy-headed programmers tend to be surprisingly flexible, and the ones who stare off into the void are often the most useful when you need them to function effectively. Overall, managers who can understand and utilize this hierarchy of programmer types in their organization may find themselves getting promoted regularly.
Of course, many people can't stand these corporate structures and prefer the simple farmer's life, raising ducks instead. Quack!
For me: Rust killed C++ but not C
I have an on-again off-again love affair with C. And in its domain it’s still unmatched: low-level close to hardware where you directly need to deal with concepts that are normal abstracted away: alignment, custom layouts, type punning, pointer tagging, different types of memory, cache coherency, DMA, kernel bypass, etc etc
Sure you can do it in rust unsafe but it’s (intentionally) a world of pain.
But, when you start needing bigger abstractions or you work with a team larger than say 5, C falls on its face super fast.
But it Feels Oh So Nice otherwise.
Here’s to me hoping Rust unsafe becomes more usable and can be a proper C successor someday. But.. I’m happy to be rid of C++ :-)
(I’ve been meaning to write a blog post on this for some time)
Getting good codegen out of Rust is 5 times harder than C. And sometimes it’s not really possible.
Can someone point me to which set of virtues you are talking about here? Simplicity? Value semantics and imperatives, little abstractions over what the computer OS is actually doing? Manual control over almost everything being done? Are such "virtues" safe and dignifying under an universal context of computer programming? Isn't it a bit dangerous to let such Virtues take over in modern programming dealing with heavy abstraction layers because of the yield in complexity of modern hardware?
What always killed me the most in C was the absolutely anemic standard library. OS’ had more libraries, but still very low level stuff.
People who chose C as the best option at the time might not be even around the project anymore.