Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef an uintX_t type, where X is the value of a macro

I have a macro, WW, with the word width in bits, like

#define WW 64

I want to declare a new type, foo_t, as an alias for one of the uintX_t in <stdint.h>. I can hard code the word width and use

#define uint(x) typedef uint ## x ## _t foo_t
uint(64);

However, uint(WW) is obviously an error. I have played around for a while using a macro like #define expand(x) x and use it in various ways, to no avail. My last resort is an #if cascade such as

#if WW == 64
typedef uint64_t foo_t;
#elif WW == 32
typedef uint32_t foo_t;
#elif WW == 16
typedef uint16_t foo_t;
#elif WW == 8
typedef uint8_t foo_t;
#else
#error "unsupported word width"
#endif

which I'd rather avoid. Is there a way to typedef a type based on my WW macro so that uint(WW) would expand eventually to uint64_t? I believe the answer is "no", but some language-lawyer please prove me wrong.

like image 406
Jens Avatar asked Sep 06 '15 12:09

Jens


1 Answers

Due to the way macro expansion works, you need an extra level of indirection:

#define maketype(x) uint ## x ## _t
#define uint(x) typedef maketype(x) foo_t

Live example

like image 56
Igor Tandetnik Avatar answered Oct 02 '22 19:10

Igor Tandetnik