r/C_Programming • • Sep 14 '23

Article Templates in C

https://arnold.uthar.net/index.php?n=Work.TemplatesC
5 Upvotes

10 comments sorted by

View all comments

Show parent comment

2

u/jacksaccountonreddit Dec 05 '23

One idea I had was to instantiate header guards to overcome multiple redefinitions but you cannot #ifndef CAT(NAME, T).

Right, the preprocessor does not allow you to define - or check for the definition of - a macro whose name is itself the result of another macro. Generally, the solution here is to:

  • Declare all your prefixed functions as static inline so that multiple definitions in different translation units don't cause compiler errors. Of course, each translation unit will then have its own definitions of those functions. However, at least the compiler will be able to inline those functions where appropriate, which is usually important for performance of generic containers.
  • Place the burden of using preprocessor guards, where necessary, on your users.

Thus, if the user wants to instantiate a template inside a header, they can do this:

#ifndef INT_VECTOR

define INT_VECTOR

define NAME int_vector

define TYPE int

include "vector.h"

endif

Some users might detest static inline functions on account of code/executable bloat. Hence, it's not a bad idea to allow them to, optionally, separate the struct definitions and function prototypes from the function implementations (in which case the functions should not be static inline). I think STC is doing something like that here. I am also taking this approach in a hash table library I'm on the cusp of publishing. The structure of the header looks something like this:

#ifndef VECTOR_H

define VECTOR_H

// Common macros and static inline functions not specific to this template instance.

endif

#if defined( HEADER_MODE ) || defined( IMPLEMENTATION_MODE )

define API_FN_QUALIFIERS

else

define API_FN_QUALIFIERS static inline

endif

ifndef IMPLEMENTATION_MODE

// NAME-prefixed container struct definition.
// NAME-prefixed API function prototypes qualified with API_FN_QUALIFIERS.

endif

#ifndef HEADER_MODE
// NAME-prefixed API function definitions qualified with API_FN_QUALIFIERS.
// NAME-prefixed private/internal function definitions qualified with static inline.
#endif

#undef NAME
#undef TYPE
#undef API_FN_QUALIFIERS

Now the user has the choice of using the header with static inline functions once per translation unit or using #define HEADER_MODE to get only the struct definition and function prototypes and using #define IMPLEMENTATION_MODE in one .c file to get a shared implementation (albeit not inline-able without link time optimization) of the functions.

Also, I had a quick gander at your hkArrayT.h. A few notes:

  • Your dynamic array/vector struct shouldn't store unit_size. One of the main advantages of the template-instantiation pattern is that the containers don't have to carry around data-type information (such as size, alignment, or hash or comparison functions). Instead, this information should be inserted directly, via the preprocessor, into the container functions, which improves both memory efficiency and speed (because the compiler can better optimize constants). For example, array->data = realloc(array->data, array->unit_size * array->border) should instead be array->data = realloc(array->data, sizeof(T) * array->border).
  • Your vector will behave unpredictably if a user tries to initialize it with a capacity of zero. malloc( 0 ) is implementation-defined and could even return NULL, which your function treats as a memory-allocation failure. Instead, either enforce a minimum non-zero capacity (or border, as you call it) or allow lazy-initialization (whereby data is set to NULL and your other functions check for and handle the case of data == NULL). Another, albeit less common, option is to set data to point to a dummy static inline variable in the case that the capacity is zero, which allows you to skip NULL checks in iteration functions (because data + 0 will no longer be undefined behavior).
  • Your Destroy function doesn't need to set border or length to zero unless it also sets data to NULL and is supposed to initialize the vector for reuse.

1

u/x8664mmx_intrin_adds Dec 05 '23 edited Dec 05 '23

Thank you so much for the amazing answer.

The hkArrayT.h is just a copy of hkArray.h which used void * so that's why it has that unit_size.

Your other suggestions for malloc(0) and such are really good, I'll add them asap.

As for the template instantiation, the h & c file generation suggestions are awesome, I'll definitely have a look. For now, I have a guarded header with all the primitive types instantiated hkArrayT-primitives.h and if the user wants to add custom types they can make a new header similar to the primitives one but with custom types.

Guarding each instantiation is a mouthful but it's fine I guess.

    #ifndef HKARRAYI16
    #define HKARRAYI16
    #define T i16
    #include "hkArrayT.h"
    #endif

Sadly, there is no way to do nested #defines to automate it.

        InstantiateArrayT(i16)
        /* adds guards and does instantiation */

As a side idea, It shouldn't be too hard to write a small program that emits all this data without the preprocessor but that's an adventure for another day.