ctypesmacros

Is there a way to determine whether a type is not defined?


I have a type Type_##type dependent on a certain macro type_create:

#define type_create(type) { \
    typedef struct { \
        type* ptr, \
    } Type_##type; \

and I have a few macros dependent on it. Now I am wondering if I can do something like #ifndef for a type, for example,

#ifndef Type_int
type_create(int);
#endif

except for types.


Solution

  • Is there a way to determine whether a type is not defined?

    The C preprocessor knows nothing about the C semantics of the code it is operating on. It cannot determine whether there is a declaration of a C data type in scope at any particular point. C specifies feature-test macros for performing this kind of test for optional features of the language, but as a C programmer, you are expected to have full knowledge of all the identifiers you declare yourself.

    Conventionally, one puts all one's needed file-scope declarations at the top of the source file, either directly or by #includeing headers at that position. Among other things, that makes it fairly easy to check what's declared if you're uncertain. For anything declared directly instead of via a header, I find that it helps to put declarations after all the #includes and to group them by kind: types, then objects, then function prototypes, then function definitions. That you are using macros to write some of your type definitions doesn't make that any less appropriate, but maybe you want to group those together within a larger group of type declarations.

    Also, if you want to use macros to declare several related things, such as a structure type and prototypes for several functions associated with it, then it probably makes sense to use a single macro to declare all of them together. It doesn't hurt to declare functions or types or external objects that you never reference, as long as those declarations are not definitions.