QuaternionsRock
QuaternionsRock

Reputation: 922

How to make types configurable with preprocessor directives in C?

As of now, I have something like the following code in the header file of my library (names changed for clarity):

#ifndef CFG_RESULT_TYPE
#define CFG_RESULT_TYPE double
#endif

#if CFG_RESULT_TYPE == float
#define result_parser strtof
#elif CFG_RESULT_TYPE == double
#define result_parser strtod
#elif CFG_RESULT_TYPE == long double
#define result_parser strtold
#else
#error "Invalid result type"
#endif

typedef RESULT_TYPE result_t

I thought this would work, and it seems to for float and double (then again, maybe it's actually undefined behavior), but not for long double. What is the correct way to implement this?

I should also add that _Generic is out of the question; I am stuck on the C99 standard for this project.

Upvotes: 0

Views: 69

Answers (1)

0___________
0___________

Reputation: 67638

#define DOUBLE 1
#define FLOAT 2
#define LONG_DOUBLE 3

#ifndef CFG_RESULT_TYPE
#define CFG_RESULT_TYPE DOUBLE
#endif

#if CFG_RESULT_TYPE == FLOAT
    #define result_parser strtof
    #define RESULT_TYPE float
#elif CFG_RESULT_TYPE == DOUBLE
    #define result_parser strtod
    #define RESULT_TYPE double
#elif CFG_RESULT_TYPE == LONG_DOUBLE
    #define result_parser   strtold
    #define RESULT_TYPE long double
#else
 #error "Invalid result type"
#endif

#ifdef RESULT_TYPE
typedef RESULT_TYPE result_t;
#endif

Upvotes: 2

Related Questions