I am trying to redefine a macro to append another macro to it.
When APPEND_ITEM is defined, I got the following error at compile time:
warning: "LIST" redefined
error: 'LIST' undeclared here (not a function)
#include <stdio.h>
#include <stdint.h>
#include "item.h"
#define LIST 1, 2, 3
#define ITEM 4
#ifdef APPEND_ITEM
#define LIST LIST, ITEM
#endif
uint8_t arr[] = {LIST};
int main()
{
for (uint8_t i = 0; i < sizeof(arr); i )
{
printf("%d ", arr[i]);
}
printf("\r\n");
return 0;
}
Expected output:
1 2 3 4
I am using GCC.
CodePudding user response:
I want to be able to change the size of arr[] variable at compile time
In this case you don't need to redefine the list (which on the other hand is not possible as others have explained since LIST
expands to its literal values when used), but you can embed the ITEM
directly into the array:
#include <stdio.h>
#include <stdint.h>
#define LIST 1, 2, 3
#define ITEM 4
#define APPEND_ITEM
uint8_t arr[] = {
LIST
#ifdef APPEND_ITEM
, ITEM
#endif
};
int main()
{
for (uint8_t i = 0; i < sizeof(arr); i )
{
printf("%d ", arr[i]);
}
printf("\r\n");
return 0;
}
CodePudding user response:
Every time the pre-compiler meets LIST in your code, it substitutes it with the contents of #define, i.e. with LIST, ITEM.
It cannot recursively get into it and look, what LIST and ITEM were previously; it's not the task. It is treated just like a piece of c-code, where the expression "LIST, ITEM" doesn't have sense.
So that just doesn't work.
But you can use functions inside of a #define.
CodePudding user response:
For readability and easy maintenance, consider using this version (no #ifdef
clutter in the middle of functions):
#include <stdio.h>
#include <stdint.h>
#define LIST_INIT 1, 2, 3
#define ITEM 4
#ifdef ITEM
#define LIST LIST_INIT, ITEM
#else
#define LIST LIST_INIT
#endif
int main()
{
uint8_t arr[] = { LIST };
for (uint8_t i = 0; i < sizeof(arr); i )
{
printf("%d ", arr[i]);
}
printf("\r\n");
return 0;
}