Lately I have been making an attempt to read more open source C code. A common pattern that I have been adopting in my hobby projects is as follows.
In my C files, I have functions that are either static or exported. Only functions that are exported are placed in a header file. Global variables which are only used within the scope of an object are also used as static global variables.
My question concerns the usefulness and motivation of having static inline
functions inside header files. From what I read online, not using the static
keyword causes a multiple definition error and that is the reason for not just defining the function as just inline
.
However, does this mean that this function is exported for other objects to use? If yes, then why not just defining this function in the C file and export it via the header file? If not, why putting this in the header file rather than just having it inside the C file?
Is there a reason behind this coding style? What am I missing?
One such example can be found in the git codebase inside hashmap.h
:
/*
* Converts a cryptographic hash (e.g. SHA-1) into an int-sized hash code
* for use in hash tables. Cryptographic hashes are supposed to have
* uniform distribution, so in contrast to `memhash()`, this just copies
* the first `sizeof(int)` bytes without shuffling any bits. Note that
* the results will be different on big-endian and little-endian
* platforms, so they should not be stored or transferred over the net.
*/
static inline unsigned int sha1hash(const unsigned char *sha1)
{
/*
* Equivalent to 'return *(unsigned int *)sha1;', but safe on
* platforms that don't support unaligned reads.
*/
unsigned int hash;
memcpy(&hash, sha1, sizeof(hash));
return hash;
}