Consider a (read-only third-party) header lib.h with:
#define XYZ 42
In a source file, I want to use the word XYZ for an unrelated purpose, and do not want the substitution with 42. But, in the same source file, for other purposes, I also do want to access the value 42 from lib.h without hardcoding it. How do I rename the macro from XYZ to, say, LIB_XYZ?
The following does not work, because preprocessor wants XYZ at the time the LIB_XYZ substitution is made, but XYZ had been undefined:
#include "lib.h"
#define LIB_XYZ XYZ
#undef XYZ
Is there a way to trick the preprocessor into expanding LIB_XYZ to its final value before XYZ is lost?
You can't. Macros are expanded by the Preprocessor, which happens even before the code is compiled. It is a purely textual replacement. If you need to change something at runtime, just replace your macro with a real function call.
The process to redefine a Macro is: Macro must be defined. When, you want to redefine the Macro, first of all, undefined the Macro by using #undef preprocessor directive. And, then define the Macro again by using #define preprocessor directive.
Syntax: int rename (const char *old_name, const char *new_name); Parameters: old_name : Name of an existing file to be renamed. new_name : String containing new name of the file.
Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.
Not with the pre-processor, at least, not that I am aware of.
However, for simple constants with known type like in your example, there is a workaround.
#include <stdio.h>
// <xyz.h>
#define XYZ 42
// </xyz.h>
enum xyz_constants
{
LIB_XYZ = XYZ,
};
#undef XYZ
#define XYZ 27
int
main()
{
printf("old value: %d, new value: %d\n", LIB_XYZ, XYZ);
return 0;
}
Not showing the fluff from stdio.h, this code is pre-processed to the following.
enum xyz_constants
{
LIB_XYZ = 42,
};
int
main()
{
printf("old value: %d, new value: %d\n", LIB_XYZ, 27);
return 0;
}
You can extend this to some degree to other data types and certain function-like macros but there are of course limits.
Anyway, why do you need the particular identifier XYZ? Can't you use a different name for your macro?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With