Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the definition of a macro as a string literal?

Say in a header, which I do not want to read myself but which I do include, I have

#define A B
#define B C

Now

#define STR(name) # name

defines a macro that gives me the name of any macro as a string, and

#define EXP_STR(name) STR(name)

defines a macro that gives me the full expansion of any macro as a string. So

cout << STR(A) << EXP_STR(A) << endl;

will print AC.

Is there any way to get "B" from A using some macros?

like image 801
not-a-user Avatar asked Jan 08 '15 16:01

not-a-user


People also ask

How do you check if a string is a literal?

If argument is literal string , it will look like "\"text\"" or "L\"text\"" and will contain characters 'L' and '\"' .

Where is __ Va_args __ defined?

The C standard mandates that the only place the identifier __VA_ARGS__ can appear is in the replacement list of a variadic macro. It may not be used as a macro name, macro argument name, or within a different type of macro. It may also be forbidden in open text; the standard is ambiguous.

How do I know if a macro is defined?

To check – A Macro is defined or not, we use #ifdef preprocessor directive. To check whether a Macro is defined or not in C language – we use #ifdef preprocessor directive, it is used to check Macros only. If MACRO_NAME is defined, then the compiler will compile //body (a set of statements written within the #ifdef ...

How do you #define in CPP?

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.


1 Answers

Since you can write

#define B C
#define A B

#define STR(name) # name
#define EXP_STR(name) STR(name)

and the

cout << STR(A) << EXP_STR(A) << endl;

will output exaclty the same, it means that it's not possible.

When you do this

#define A B

and then

#define B C

now this means that A will be substituted by C and not B, so there will be no way to do it because when the cout line is reached the preprocessor had already substituted A by C.

So the short answer is, it's not possible because the preprocessor would have replaced A with C before the file is compiled.

like image 75
Iharob Al Asimi Avatar answered Sep 21 '22 06:09

Iharob Al Asimi