简体   繁体   中英

How can I check if I implement C library functions correctly?

Is there any source/database for basic C library functions (like strcmp , memset , etc)?
I want to implement basic C library functions but I can't verify if I'm doing it right or not.

I found several source code databases but they are far more complicated than they should be (eg the implementation of strcpy is more than 30 lines, half of it isn't related to copying the strings, I think).

The "basic" C library functions are also some of the most important for program performance and correctness, and so tend to have some complicated implementations.

I suggest you look at the code for Newlib . It's a basic C library intended for embedded systems (your TV might well run it) and it also used in Cygwin. The license is also mostly compatible with "borrowing" source for your own purposes, but be careful because some bits of it (some files) are GPL.

Check out the OpenBSD C library . Eg, here's its basic strcpy :

char *
strcpy(char *to, const char *from)
{
    char *save = to;

    for (; (*to = *from) != '\0'; ++from, ++to);
        return(save);
}

Documentation for the functions is included in the form of manpages.

(It also carries optimized versions of common routines, usually in assembler, so the C versions should really be regarded as reference implementations.)

There's a great book The Standard C Library from PJ Plauger. It's a bit dated (1992), but still valuable resource if you want to implement libc and do it right. It contains full code to the library. There is also musl libc . The code lives in git repo. The implementation is not straightforward, but if I compare it to other implementations it's really small and simple. And as somebody else already mentioned the C standard is something you want to look at.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM