Home > OS >  Changing a macro in C (or C )
Changing a macro in C (or C )

Time:05-12

In other words, how can I redefine a macro based on it's previous definition? Specifically, I want to add a string to the end of a string macro in C . This is what I've tried so far:

#define FOO "bla"
// code here will read FOO as "bla"
#define FOO FOO ## "dder"
// code here will read FOO as "bladder"

In C , this returns error: FOO was not declared in this scope. How would I do this without getting this error?

EDIT: I've read the comments and found out what an "XY problem" is. What I want to do is make a library for C but the library is written in C . Because the library requires Classes to function (because it uses other C libraries), I wanted to make an empty class that the C program using the library can add custom properties to using Macro functions. Something like this:

// lib.h

#define PROPERTIES ""
#define NEW_PROPERTY(X) // add X   ";\n" to PROPERTIES (somehow)

#ifdef __cplusplus
Class myclass
{
    public:
        PROPERTIES
}
#endif

_

// c code
#include <lib.h>

NEW_PROPERTY(int id);
NEW_PROPERTY(int color);

int main(){
...

The c program won't need to access the properties because they only exist so that a third-party library that is a dependency for my library can use them.

CodePudding user response:

This is not possible.

From the gcc documentation (emphasis is mine):

However, if an identifier which is currently a macro is redefined, then the new definition must be effectively the same as the old one. Two macro definitions are effectively the same if:

  • Both are the same type of macro (object- or function-like).
  • All the tokens of the replacement list are the same.
  • If there are any parameters, they are the same.
  • Whitespace appears in the same places in both. It need not be exactly the same amount of whitespace, though. Remember that comments count as whitespace.

These definitions are effectively the same:

#define FOUR (2   2)
#define FOUR         (2         2)
#define FOUR (2 /* two */   2)

but these are not:

#define FOUR (2   2)
#define FOUR ( 2 2 )
#define FOUR (2 * 2)
#define FOUR(score,and,seven,years,ago) (2   2)

If a macro is redefined with a definition that is not effectively the same as the old one, the preprocessor issues a warning and changes the macro to use the new definition. If the new definition is effectively the same, the redefinition is silently ignored. This allows, for instance, two different headers to define a common macro. The preprocessor will only complain if the definitions do not match.

  • Related