Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

C is actually one of the few languages that gets the language/library separation mostly right. You can write pretty much the entire standard library in C, and you can easily write C without the standard library. It's very straightforward (if sometimes a bit annoying) to do this in Windows, and I believe neither EPOC/Symbian or PalmOS supported the ISO C library.

varargs, setjmp/longjmp and sbrk are 100% library. You can do varargs without stdarg.h; if you know the calling convention, you can just walk through the memory occupied by the arguments. setjmp is trickier but if you know the rules you could write it using assembly language, just like the library writers did. As for sbrk, I'm not terribly familiar with that I do admit, but judging by the man page it is not part of the C standard library, kind of proving my point. But you can definitely have a heap, and allocate out of it, and (where plausible) grab more address space, without having it.



I agree with your broad point that you can write a usable C library with a very minimal amount of assembly, but I am going to quibble on some of the details.

> You can write pretty much the entire standard library in C, ... varargs, setjmp/longjmp and sbrk are 100% library.

If you're saying "These four functions can be written in C" then you are mistaken. If you are saying "These four functions can be written in assembly" then you are not saying anything interesting about C, because it is true of any language that it is possible to write its library in assembly if it's possible to write it at all.

In more detail.

Whether you can write va_arg in C depends on the platform's calling convention. On most platforms you can (because the default calling convention has to support varargs, and the easiest way to do that is to push the arguments on the stack) but on x86-64 you can't.

setjmp and longjmp cannot be written in C on any platform I'm familiar with, unless you're writing them on top of something like setcontext, which has a slight superset of their functionality. They are, however, very simple to write in assembly.

You can write sbrk in one line of C, and the glibc implementation is only ten: http://koala.cs.pub.ro/lxr/glibc/misc/sbrk.c#L29 But sbrk is simply a convenience wrapper around brk, which is necessarily a system call. And C doesn't have a "system call" statement.

(Actually, you can write brk in C too if you just want to allocate out of some fixed blob of address space, which is a reasonable choice on, say, a microcontroller.)


Varargs for the X86_64 is most definitely baked into the compiler, and impossible to do library only.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: