1) Why is the macro MSG not expanded in the following expression?
#define MSG Hello
#define HELLO(name) MSG ## name
void HELLO(Dave) () {}
Using
gcc -E -P test.cpp
Output:
void MSGDave () {}
MSG name expands to Hello Dave. And MSG # name expands to Hello "Dave". So what causes gcc not to expand MSG ## name?
2) Is there a workaround?
Is there a preprocessor directive like defined(x), such as expand(x)?
Because macro arguments are not substituted when preceded or followed by a ## operator.
C11 §6.10.3.1 Argument substitution
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is
replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.
#define MSG Hello
#define cat(x, y) x ## y
#define cat2(x, y) cat(x, y)
#define HELLO(name) cat2(MSG,name)
Live demo # ideone.
Related
This macro is not expanding as I thought it would, I have the following macro (source is from Analog Devices so I cannot change this):
#define SRU(out,in) \
r0=dm(in##_REG); \
r1=sru_mask(out,in); \
r0=r0 and r1; \
r1=sru_field(out,in); \
r0=r0 or r1; \
dm(in##_REG)=r0;
Normally you would use it as
SRU (LOW, DAI_PB14_I);
But I want to create a HW configuration header so I defined:
#define DTS_SEL_DSP_I DAI_PB14_I
So the usage above would be:
SRU (LOW, DTS_SEL_DSP_I);
But I get the error
error: identifier "DTS_SEL_DSP_I_REG" is undefined
it should be "DAI_PB14_I_REG"
So the macro is stringifying the actual symbol and not the value I defined, how can I get around this?
So the macro is stringifying the actual symbol and not the value I defined
Yes, this is the specified behavior for the token pasting operator. Its operands are not macro-expanded before being pasted together. If the pasted-together result is a macro name, then it will be expanded on the rescan.
, how can I get around this?
Since you cannot modify the SRU macro, the best workaround would probably be to wrap it, which should be very simple:
#define MY_SRU(out,in) SRU(out,in)
Since they are not operands of the ## or # operator, the arguments to MY_SRU will be fully macro expanded. The resulting invocation of SRU with expanded arguments is itself expanded on the rescan.
Suppose I have this code:
#define NAME MY_APP
#define ENABLE NAME ## _ENABLE
I want to check if the macro that ENABLE expands to is defined, i.e., if MY_APP_ENABLE is defined. Is this possible using C macros?
You can use the construct defined to check if a macro is defined, but it's only possible to use this in preprocessor expressions. It's possible to write a macro that expands to this construct. For example:
#define MY_APP_ENABLED
#define IS_DEFINED(x) defined(x ## _ENABLED)
#if IS_DEFINED(MY_APP)
#error "YES"
#else
#error "NO"
#endif
The above will issue YES when compiled. If MY_APP_ENABLED isn't defined, NO will be issued.
Update: The following version will work when NAME is defined to MY_APP. The extra level of indirections allows NAME to be expanded to MY_APP before it's concatenated with _ENABLED:
#define MY_APP_ENABLED
#define IS_DEFINED0(x) defined(x ## _ENABLED)
#define IS_DEFINED(x) IS_DEFINED0(x)
#define NAME MY_APP
#if IS_DEFINED(NAME)
#error "YES"
#else
#error "NO"
#endif
No. In particular, the suggested
#ifdef NAME ## _ENABLE
will not work, according to 6.10.3.4 Rescanning and further replacement, which says
The resulting completely macro-replaced preprocessing token sequence is not reprocessed as a preprocessing directive even if it resembles one, but all pragma unary operator expressions within it are then processed as specified in 6.10.9 below.
Given the following macros giving access to compiler attributes in a function-call way, like spec(section(".mysection")) void foo(void);:
#define spec(_H_) spec_##_H_
#define spec_section(_S_) attribute ((section (_S_)))
I now would like to use these definitions in other macros, like spec(namespace(unmanaged)) int x;:
#define spec_namespace(_H_) spec_namespace_##_H_
#define spec_namespace_unmanaged spec(section(".unmanaged"))
But this does not expand at all, the only way to make it work is writting the expanded spec() macro myself:
#define spec_namespace_unmanaged spec_section(".unmanaged")
Any idea of what is going on? gcc -E on spec(namespace(unmanaged)) results inspec(namespace(unmanaged)).
Citing C99 draft 6.10.3.4 Rescanning and further replacement §2 (emphasis mine):
If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later(re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
From folowing macro-definitions:
#define spec(_H_) spec_##_H_
#define spec_namespace(_H_) spec_namespace_##_H_
#define spec_namespace_unmanaged spec(section(".unmanaged"))
It's clear that spec macro is evaluated twice, so no futher replacement is done, let's take it step-by-step:
spec(namespace(unmanaged)) int x; → spec_namespace(unmanaged) int x;
spec_namespace(unmanaged) int x; → spec_namespace_unmanaged int x;
spec_namespace_unmanaged int x; → spec(section(".unmanaged")) int x;
What you can do about it is to modify your last macro-defintion into following form:
#define spec_namespace_unmanaged attribute ((namespace (".unmanaged")))
or maybe simplify it as:
#define spec(_H_) spec_##_H_
#define spec_section(_S_) attribute ((section (_S_)))
#define spec_namespace(_N_) attribute ((namespace (_N_)))
with:
spec(namespace(".unmanaged")) int x;
To put it simply, the preprocessor will only expand a nested macro on the left side (in another macro's arguments) if neither the stringification operator # nor the concatenation operator ## are applied to it on the right side (in the macro definition).
The idiomatic way to force a nested macro expansion is to use a helper macro:
#define macro_helper(x) macro(x) // gets x expanded
Consider the following example which gets the nested __LINE__ macro expanded:
#include <iostream>
#define MACRO1(L) "Line " #L // MACRO1(__LINE__) -> "Line " "__LINE__")
#define MACRO2 MACRO1(__LINE__) // MACRO2 -> MACRO1(__LINE__)
#define MACRO3(L) "Line " #L // MACRO3(13) -> "Line " "13")
#define MACRO4(L) MACRO3(L) // MACRO4(__LINE__) -> MACRO3(13)
#define MACRO5 MACRO4(__LINE__) // MACRO5 -> MACRO4(__LINE__)
int main()
{
std::cout << MACRO2 << std::endl; // Output: "Line __LINE__"
std::cout << MACRO5 << std::endl; // Output: "Line 13"
}
This question already has answers here:
The ## operator in C
(7 answers)
Closed 4 years ago.
something like #NAME or ##NAME. what do they mean in C? I saw them in GCC documents about macro.
operator ## concatenates two arguments leaving no blank spaces between them..
#define printe(a,b) a ## b
printe(c,out) << "testing";
output is : testing
and single # is used for parameter replacement withe the string parameter
like
#define st(x) #x
cout<<st(tesing); // equivalent to cout<<"testing";
and # is also a preprocessor directive..
A code statement beginning with # indicates what follows is a preprocessor directive and should be expanded by the pre-processor.
## is called token Pasting or Token concatenation macro.
From the wikipedia page describing the C preprocessor:
The ## operator concatenates two tokens into one token, as in this example:
#define DECLARE_STRUCT_TYPE(name) typedef struct name##_s name##_t
DECLARE_STRUCT_TYPE(g_object); // Outputs typedef struct g_object_s g_object_t;
The # operator signals other directives to the C preprocessor, for example: #include, #define, #undef, #error, #if, #ifdef, #ifndef, #else, #elif, #endif
The '#' is really not an operator, they are preprocessor directives, and the '##' is used only for function macro definitions.
There are many preprocessor directives in C:
For Macro Definitions there are:
#define
#undef
For Conditional Inclusions, there are:
#ifdef
#ifndef
#if
#endif
#else
#elif
For Line Control, there is:
#line
For Error, there is:
#error
For Source file inclusion, there is:
#include
For Pragma directive, there is:
#pragma
For more information, read this http://www.cplusplus.com/doc/tutorial/preprocessor/
I'm trying to use preprocessor tricks to declare a magic variable. Something like this:
DECLARE(x)
should expand to
int _DECLARED_VARIABLE_x_LINE_12
if the declaration was on line 12 of the input source. I was trying to use the ## token-pasting command and the __LINE__ macro, but I either get an uninterpreted "__LINE__" in there or the preprocessor seems to completely ignore my line. My current guess is:
#define DECLARE(x) _DECLARED_VARIABLE_ ## x ## _LINE_ ## __LINE__
The normal trick in such cases is to use a second macro. However, that does not seem to work with GCC (4.5.1 on MacOS X 10.6.4), and a third level of macro was needed:
#define DECLARE(x) _DECLARED_VARIABLE_ ## x ## _LINE_ ## __LINE__
#define DECLARE42(x, line) _DECLARED_VARIABLE_ ## x ## _LINE_ ## line
#define DECLARE41(x, line) DECLARE42(x, line)
#define DECLARE40(x) DECLARE41(x, __LINE__)
int DECLARE(y);
int DECLARE40(c) = 129;
Output of 'gcc -E':
# 1 "magicvars.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "magicvars.c"
int _DECLARED_VARIABLE_y_LINE___LINE__;
int _DECLARED_VARIABLE_c_LINE_8 = 129;
I'm not sure I have a good explanation of why the third level of macro was needed.
I am also curious to know how you are ever going to refer to these variables after you've created them.
I went through a number of variations before managing to hit on the one that worked:
#define DECLARE(x) _DECLARED_VARIABLE_ ## x ## _LINE_ ## __LINE__
#define DECLARE11(x, line) _DECLARED_VARIABLE_ ## x ## _LINE_ ## line
#define DECLARE10(x) DECLARE11(x, __LINE__)
#define DECLARE23(line) _LINE_ ## line
#define DECLARE22(x) _DECLARED_VARIABLE_ ## x
#define DECLARE21(x, line) DECLARE22(x) ## DECLARE23(line)
#define DECLARE20(x) DECLARE21(x, __LINE__)
#define DECLARE32(line) _LINE_ ## line
#define DECLARE31(x, line) _DECLARED_VARIABLE_ ## x ## DECLARE32(line)
#define DECLARE30(x) DECLARE31(x, __LINE__)
#define DECLARE42(x, line) _DECLARED_VARIABLE_ ## x ## _LINE_ ## line
#define DECLARE41(x, line) DECLARE42(x, line)
#define DECLARE40(x) DECLARE41(x, __LINE__)
int DECLARE(y);
int DECLARE10(z) = 12;
int DECLARE20(a) = 37;
int DECLARE30(b) = 91;
int DECLARE40(c) = 129;
Have fun working out why the non-working ones didn't work. They did, however, point me towards the working answer. (I note that the Sun C compiler produces essentially the same results as GCC on the same input.)
The preprocessor removes the ## operators from the macro replacement list before attempting to look for further macros for recursive replacement. This means that your reference to __LINE__ gets "glued" to the rest of the macro before it has a chance to get recognized as __LINE__ and replaced with the actual line number.
For this reason, if you want to embed the line number into your macro, you have no other choice but to pass it through a macro parameter
#define DECLARE_(x, L) _DECLARED_VARIABLE_##x##_LINE_##L
#define DECLARE(x) DECLARE_(x, __LINE__)
And that will formally solve the immediate problem in your original macro definition.
However, this still will not work as expected due to another quirk in C/C++ preprocessor specification: parameter names adjacent to ## are replaced with the corresponding arguments values without the recursive macro expansion in the argument value. I.e. L will be replaced with __LINE__, without changing __LINE__ to the actual line number first.
To ensure the recursive macro expansion for parameter L, one needs to introduce another "level of indirection" in macro definition
#define DECLARE__(x, L) _DECLARED_VARIABLE_##x##_LINE_##L
#define DECLARE_(x, L) DECLARE__(x, L)
#define DECLARE(x) DECLARE_(x, __LINE__)
In this case, when processing DECLARE_(x, L) macro, the preprocessor will handle L recursively: first replace it with __LINE__ and then replace __LINE__ with the actual line number. DECLARE__ will receive the complete line number.
There was an issue with __LINE__ in debug mode with Visual Studio if you were using Edit and Continue. Here is a reference to it. That issue is a few years old though. If that issue is resolved, then Jonathan Leffler's solution will work fine.
There are two special expansion rules regarding ## operator:
Operands to ## operator are not expanded before pasting.
Macro arguments are not expanded if they are concatenated with ##.