Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a C preprocessor macro?

Tags:

c

macros

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?

like image 965
alexei Avatar asked Jan 13 '16 00:01

alexei


People also ask

Can you change macros in C?

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.

How do I redefine a macro?

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.

How do you rename a function in C?

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.

What is a macro name in C?

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.


1 Answers

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?

like image 130
5gon12eder Avatar answered Nov 01 '22 13:11

5gon12eder