Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing macro arguments by macro

Tags:

c

gcc

macros

I'm trying to pass a RGB color into a macro that takes three arguments. A normal call would look like this: MACRO(255, 255, 255) The macro converts the arguments and together with an operator it is then sent over SPI to a graphics controller. A call in C code looks like this: cmd(MACRO(0,0,0));

As the color is used on multiple occasions, but might be subject to change, i thought it might be a good idea to define it via another macro. So defining a color e.g. #define BLACK 0,0,0 and inserting it into the other macro should be ok: MACRO( BLACK ) -> cmd(MACRO( BLACK )); But the compiler outputs an error:

macro "MACRO" requires 3 arguments, but only 1 given

Getting this i assume the macro providing the arguments is not being expanded. I tried to figure out what was wrong reading through the gcc macro documentation, but was not able to sole it. I assume it is one of those stupid simple things... Thank you!

More info: There are multiple macros provided by a driver taking three numbers (rgb) as an argument. I would like to define a color scheme to be able to change a color for every occurrence without changing more than those three numbers.

The function where the macro is inserted is taking an unsigned long and that is what the macro is producing.

Why is the term BLACK not simply substituted by 0,0,0?

Quote from the gcc macro documentation:

"All arguments to a macro are completely macro-expanded before they are substituted into the macro body. After substitution, the complete text is scanned again for macros to expand, including the arguments."

like image 461
HeidiSalami Avatar asked Jan 07 '23 23:01

HeidiSalami


2 Answers

You'd have to ensure that your combination MACRO(BLACK) evaluates the BLACK part once more. Otherwise it doesn't "see" the commas separating the zeros. What you could to is rename your existing MACRO to MACRO3 (it receives 3 arguments) and then have

#define MACRO(...) MACRO3(__VA_ARGS__)
like image 103
Jens Gustedt Avatar answered Jan 14 '23 20:01

Jens Gustedt


You may want to define your macro like this:

#define MACRO(x, y, z) somestuffhere
#define BLACK MACRO(0,0,0)

And then call it like that

cmd(BLACK);

This is a more logical implementation. If you define a macro that take 3 arguments, it should take 3 arguments and not one. However you can call macro inside another macro definition.

like image 24
Louis Ventre Avatar answered Jan 14 '23 19:01

Louis Ventre