Substitute just once, concatenate, and substitute again [duplicate] - c

This question already has answers here:
How to force macro to not expand
(1 answer)
Pre-processor: Expand a macro only once
(3 answers)
C: is it possible to expand marcos before pasting, but not recursively?
(1 answer)
Closed 9 months ago.
Given macro definitions like this:
#define GPIOA ((1234)+42)
#define GPIOB ((1234)+84)
#define LEDA_GPIO_Port GPIOA
#define LEDB_GPIO_Port GPIOB
#define MY_PORT_GPIOA 0
#define MY_PORT_GPIOB 1
I would like to define a macro MY_PORT which, given LEDA as argument somehow substitutes this to LEDA_GPIO_Port, then to GPIOA, turns that into MY_PORT_GPIOA and this into 0. So MY_PORT(LEDA) should evaluate to 0 and MY_PORT(LEDB) to 1. If the macros GPIOA/GPIOB wouldn't exist, this would be easy, but since they are defined as complex expressions (starting with parentheses) only one substitution must be performed, and the occurence of GPIOA must not be substituted by that expression.
I tried
#define MY_PORT2(port) MY_PORT_##port
#define MY_PORT(name) MY_PORT2(name##_GPIO_Port)
but here MY_PORT(LEDA) returns MY_PORT_LEDA_GPIO_Port, i.e. it lacks one substituion.
#define CONCAT(a,b) a##b
#define MY_PORT2(port) CONCAT(MY_PORT,port)
#define MY_PORT(name) MY_PORT2(name##_GPIO_Port)
does not compile, as it tries to concatenate the definition for GPIOA, i.e. one subtitution too many.
Is it even possible to do exactly one subtitution?

Related

The C define with any value for non zero

In C I have a define like:
#define VALUE 5
But the user can set a function too:
#define VALUE get_value()
For historical reasons
#define VALUE 0
means "the value is not set, use the default"
The question is how to write an #if that decides if VALUE is 0.
#if VALUE == 0
...
#else
...
#endif
gives "missing binary operator before token "("" error with GCC.
EDIT:
To make the use case clearer:
#if VALUE == 0
set_default_value();
#else
set_value(VALUE)
#endif
So I don't need VALUE to be evaluated in the #if just see if it's literally '0' or not.
You can use preprocessing pattern matching.
#define SECOND(...) SECOND_I(__VA_ARGS__,,)
#define SECOND_I(A,B,...) B
#define GLUE(A,B) GLUE_I(A, B)
#define GLUE_I(A,B) A##B
#define ZERO_TEST(X_) SECOND(GLUE(ZERO_TEST_AGAINST_,X_),0)
#define ZERO_TEST_AGAINST_0 ,1
The key construct here is the SECOND macro, which indirectly expands to its second argument. For pattern matching, you would use this by carefully constructing a first argument; since SECOND normally expands to its second argument, whatever you construct is normally ignored. But since SECOND expands to its second argument indirectly, you can cherry pick a particular pattern by having the first argument expand in particular cases with a comma, which would shove in a new second argument.
In this case we have an indirect paste at the end of ZERO_TEST_AGAINST_, and we're looking for the result of that to be ZERO_TEST_AGAINST_0.
To use this:
#if ZERO_TEST(VALUE)
set_default_value();
#else
set_value(VALUE)
#endif
Demo
http://coliru.stacked-crooked.com/a/2a6afc189637cfd3
Caveat
This fits your spec precisely as given; the indirect paste would not work with this form if you have parenthetical definitions:
#define VALUE (5)
...or:
#define VALUE (get_value() << 2) | 1
...since ZERO_TEST_AGAINST_ and ( do not join to make a valid token.
A generic solution is likely impossible, but you can hack something together:
#define CAT(x, ...) CAT_(x, __VA_ARGS__)
#define CAT_(x, ...) x##__VA_ARGS__
#define CHECK_VALUE_CHECK_0 )(
#define CHECK_VALUE_FALSE(...) CHECK_VALUE_TRUE
#define CHECK_VALUE_TRUE() 1
#define CHECK_VALUE CHECK_VALUE_(CAT(CHECK_VALUE_CHECK_, VALUE))
#define CHECK_VALUE_(...) CHECK_VALUE_FALSE(__VA_ARGS__)
#if CHECK_VALUE
#error Value is 0.
#else
#error Value is not 0.
#endif
Now, if VALUE is defined to 0, the macro CHECK_VALUE will expand to 1. Otherwise it will expand to CHECK_VALUE_TRUE, which as an unknown identifier, is considered falsey by #if.
This solution is hacky:
If VALUE starts with 0,, its causes a hard error.
If VALUE starts with something other than a letter or digit or _ (e.g. (), it causes a hard error.
...
A preprocessor cannot evaluate C-Functions, such as get_value(). It can only handle static data, as its replaced with code prior to compilation, so your statements are not executed at runtime.
if (VALUE == 0) in your C-Code would get replaced for example with if (get_value() == 0) prior to compilation. The Preprocessor is not able to evaluate the return value of get_value() (even if it would always return 0).
A #define VALUE 5 line makes the C preprocessor replace the string VALUE with the string 5 wherever it sees it (outside "strings", that is). The resulting program will not even contain VALUE anymore, and that is what the compiler proper sees(1).
Do an experiment: Get your program (cut it down to a few lines), and run:
cc -E proggie.c > proggie.i
Under Unixy systems you'll get a file proggie.i that contains preprocessed C, which is what the compiler proper sees. No VALUE in sight, and trying to set VALUE in the source ends up as trying to set 0, which obviously won't work.
(1) Historically, C compilers ran a chain of programs over the source (then memories where measured in KiB, not GiB), the first --preprocessor-- was usually called cpp; today's compilers usually don't have a separate preprocessor anymore. But conceptually the first step is still preprocessing the code (handle #include, #if and #defined macros).
I think you're misunderstand how the historical 'the value is not set' works.
In the C preprocessor, whenever you have an #if directive any identifier in the expression that is not an macro (and is not the special function defined) will be replaced by the constant 0 prior to evaluating the #if. So with your example
#define VALUE get_value()
#if VALUE == 0
what happens is the VALUE macro is expanded, then, since there is no get_value macro defined, it is replaced by 0, leaving you with
#if 0() == 0
which gives you the syntax error you see.

Proper usage of #if directive in C? [duplicate]

This question already has answers here:
How to compare strings in C conditional preprocessor-directives
(14 answers)
Closed 2 years ago.
The following structure for C preprocessor directive #if works well.
#define C 1
#if C==1
...
#endif
But I'd like to use something like this:
#define REAL double
#if REAL==double
...
#elif REAL==float
...
#else
assert(0);
#endif
It's not valid. Is there a solution?
Is there a solution?
There is a whole world of ways you can combine macro expansion with conditional compilation. It's unclear which of them you would consider a solution, but here's a possibility:
#define doubledouble 1
#define floatfloat 1
#define concat_literal(x,y) x ## y
#define realtype(t1,t2) concat_literal(t1,t2)
// ...
#define REAL float
#if realtype(REAL, double)
// REAL is double
#elif realtype(REAL, float)
// REAL is float
#else
// REAL is something else
#endif
The realtype macro works by macro-expanding its arguments and concatenating them together. On rescan, if the result is doubledouble or floatfloat then that is expanded further to 1. If it is an identifier that is not defined as a macro name, then the #if treats it as 0.
It's not foolproof, of course. It does not work if REAL has a multi-token expansion, such as long double. There's also a minor risk of collision with other defined macro names.

C macro expand in another C macro [duplicate]

This question already has answers here:
How can I concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?
(3 answers)
Closed 4 years ago.
I have something like :
#define NBR 42
#define THE_ANS_IS theAnsIsNBR
Currently the second macro is expand as 'theAnsIsNBR' as expected, but i want it to be expand as 'theAnsIs42' i am not sure if it is even possible !?
#define Paste(x, y) x##y
#define Expand(x, y) Paste(x, y)
#define NBR 42
#define THE_ANS_IS Expand(theAnsIs, NBR)
#define _CONCAT(x,y) x ## y
#define CONCAT(x,y) _CONCAT(x,y)
#define NBR 42
#define THE_ANS_IS CONCAT(theAnsIs, NBR)
This works because ## concatenates two tokens. The problem is, they aren't expanded first. But calling another macro on them expands them, therefore you need to nest two function-like macros here.

Concatenation macro not properly expanding macro parameter

The macro of interest (IOPORT_CREATE_PIN) is part of a library and works as desired in general. It converts a specific pin on a specific port to a library internal unique numeric representation.
It is defined as:
#define IOPORT_CREATE_PIN(port, pin) ((IOPORT_ ## port) * 8 + (pin))
Normal usage would be
IOPORT_CREATE_PIN(PORTD, 4)
for example, which would just concatenate IOPORT_ and PORTD to IOPORT_PORTD. IOPORT_PORTD in this example is an internal definition of the library that further expands to numeric value.
However, since PORTD (defined as #define PORTD (*(PORT_t *) 0x0660), which is not really relevant here) is already part of another definition
#define FLASHPORT PORTD
So using
IOPORT_CREATE_PIN(FLASHPORT, 4)
wrongly concatenates to IOPORT_FLASHPORT instead of the desired IOPORT_PORTD inside the IOPORT_CREATE_PIN definition.
I had a look at this interesting answer and tried to apply one level of indirection hoping the macro would be properly expanded, but I wasn't able to get it right.
Is there a way to "wrap" that macro somehow to make the compiler evaluate FLASHPORT to PORTD before the concatenation?
EDIT:
As John pointed out the problem with wrapping is, that FLASHPORT would be expanded recursively, not just from FLASHPORT to PORTD, but to (*(PORT_t *) 0x0660).
Is there any workaround?
Normally, the arguments to a function-like macro are themselves macro-expanded before being substituted into the macro's replacement text. Argument expansion is suppressed, however, for macro arguments that are operands of the concatenation (##) or stringification (#) operator -- that's the reason for performing a double-expansion if you want to concatenate or stringify a macro's replacement value instead of its name.
I can not change the IOPORT_CREATE_PIN macro. Is there a way to "wrap" that macro somehow to make the compiler evauate FLASHPORT to PORTD before the concatenation?
My understanding is that you want to define a new macro, e.g. WRAPPER() that you can invoke instead of IOPORT_CREATE_PIN(), whose expansion is the same as IOPORT_CREATE_PIN() for arguments PORTD, 4, and whose expansion does not change same when FLASHPORT is used instead of PORTD as the first argument.
Whether that is doable depends in part on the macro arguments. Generally, a straight-up wrapper does what I understand you to be asking for:
// For illustrative purposes:
#define IOPORT_PORTD correct!
#define IOPORT_FLASHPORT wrong!
// As specified in the question:
#define FLASHPORT PORTD
#define IOPORT_CREATE_PIN(port, pin) ((IOPORT_ ## port) * 8 + (pin))
// Wrapper:
#define WRAPPER(port,pin) IOPORT_CREATE_PIN(port, pin)
// Demo:
Direct call: IOPORT_CREATE_PIN(FLASHPORT, 4)
Wrapped call: WRAPPER(FLASHPORT, 4)
Wrapped call: WRAPPER(PORTD, 4)
The preprocessor exands that to:
Direct call: ((wrong!) * 8 + (4))
Wrapped call: ((correct!) * 8 + (4))
Wrapped call: ((correct!) * 8 + (4))
The catch here is that if PORTD is defined as a macro in its own right, then you are hosed. You then cannot just expand FLASHPORT to PORTD; if FLASHPORT is expanded then the result of that expansion will be expanded again, recursively, before it is substituted.
Alternative Approach
As far as I know or can determine, it is not possible to create a general-purpose alias for a preprocessor macro. Where no token-pasting or stringification is involved, you can do as you have done, and simply define one macro to expand to the name of another, but that doesn't play well with pasting or stringification.
If a for-purpose solution is acceptable, however, then there are alternatives. For example, if you can identify all the token-pasting operations that can involve your alias, then you can provide aliases for the pasted-together macros, too. In your case, that might look like this:
// For illustrative purposes:
#define IOPORT_PORTD correct!
#define PORTD OOPS
// As specified in the question:
#define FLASHPORT PORTD
#define IOPORT_CREATE_PIN(port, pin) ((IOPORT_ ## port) * 8 + (pin))
// Patch up the token-pasting:
#define IOPORT_FLASHPORT IOPORT_PORTD
// Demo:
Direct call: IOPORT_CREATE_PIN(FLASHPORT, 4)
The preprocessor expands that to
Direct call: ((correct!) * 8 + (4))
That doesn't scale well, of course, and it requires some knowledge or study of the overall macro set involved, but it would solve the limited-scope problem presented in the question.
Try this:
#define MY_IOPORT_CREATE_PIN(port, pin) IOPORT_CREATE_PIN(port ,pin)
and then use MY_IOPORT_CREATE_PIN instead of IOPORT_CREATE_PIN

Glue constant with macro in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C preprocessor and concatenation
I have the macro
#define BUS B
I want to make macro BUS_PORT that expands to PORTB.
I did following:
#define BUS_PORT PORT ## BUS
But BUS_PORT expands to PORTBUS. What I did wrong? How to make it right?
As explained in this answer, you need an extra level of indirection. E.g.
#define BUS B
#define PASTER(x,y) x ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define BUS_PORT EVALUATOR(PORT, BUS)

Resources