Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the gcc preprocessor to check if an expression evaluates to a value or nothing?

I'm using gcc (specifically avr-gcc).

So this is my conundrum:

Let's say I have these defined somewhere:

#define THING_0_A 0
#define THING_0_B 1
#define THING_1_A 0

Then in a second file I have this:

#define CONCAT_(A,B,C) A ## B ## C
#define CONCAT(A,B,C) CONCAT_(A,B,C)

#define ID 0

#define THING_N(A) CONCAT(THING_,ID,A)

With this I now have a selection of expressions (still in the second file):

THING_N(_A) // evaluates to 0
THING_N(_B) // evaluates to 1
THING_N(_C) // evaluates to... nothing? Or undefined? Or THING_0_C?

Now, what I'm trying to work out is how to do this (also still in the second file):

#ifdef THING_N(_A)
    // Do something knowing that THING_N(_A) is defined (in this case THING_0_A)
#endif

Or:

#if THING_N(_A)
    // Do something knowing that the value THING_N(_A) evaluates to is defined and not just "nothing"
#endif

Of course neither of these work because #ifdef can't take an expression as an argument (and it would end up as "#ifdef 0" anyway), and THING_N(_A) evaluates to 0 within #if.

In other words, I'm looking for a way to make the preprocessor evaluate:

THING_N(_A) to true
THING_N(_B) to true
THING_N(_C) to false
THING_N(_D) to false
etc...

to be used in a conditional.

like image 523
Henry Avatar asked Apr 19 '16 12:04

Henry


1 Answers

Try this:

#if (1-THING_N(_A)-1 != 2)

This will be true for every value of THING_N(_A) (except for the value -2). It will be false only if THING_N(_A) is undefined or defined empty.

If there is a chance your macro can expand to -2, you can modify the second 1 and the 2 to other literals of your choice so that the basic idea holds.

like image 80
atturri Avatar answered Oct 16 '22 14:10

atturri