Macro expansion in C++ - c++

How can I define a macro (or a workaround for this) where the parameter is at the beginning of the line?
#define SINGLETON_IMPLEMENTATION(className) \
##className* ##className::instance_ = NULL;
This give a compiler warning (GCC 3.2.3): " '##' cannot appear at either end of a macro expansion"

You only need ## to append a parameter to another string. Your macro can be recast as
#define SINGLETON_IMPLEMENTATION(className) \
className* className::instance_ = NULL;

## is the concatenation operator; the compiler is just complaining about that.
You cannot concatenate a token without something before it, i.e. at the beginning of the macro expansion; just try to remove the ## at the beginning of the second line.
Also the second ## seems wrong. If you just want to initialize a singleton pointer, remove both ##s from your macro.

Related

Structure of #define Macro

I found this arcane construct inside include/linux/wait.h
#define DEFINE_WAIT_FUNC(name, function) \
wait_queue_t name = { \
.private = current, \
.func = function, \
.task_list = LIST_HEAD_INIT((name).task_list), \
}
I know good amount on macros and preproc directives in general, but I am absolutely lost on this one. Can someone please explain the above code structure in detail including the '\' at the end of the line. Thanks.
Note: I dont need to know what it does in linux, only the syntactic meaning behind it.
The \ character in a macros is a line continuation character. It simply allows the macro to span multiple lines.
The macro (presumably) is asociating an structure with a function pointer and doing common initialization. Lest say you want to add those structures to a list and then (during an execution step) call different functions.
A better question would at least include wait_queue_t definition.
As per others (and many references on-line), the \ character continues any line via the c-preprocessor. As for the rest,
#define DEFINE_WAIT_FUNC(name, function) \
Definition of the macro.
wait_queue_t name = { \
Declares a wait_queue_t with the macro substitution name.
.private = current, \
Initialize the private wait_queue_t structure member with the current task pointer. This is also a macro (perhaps inline assembler) defined by each architecture in the Linux tree.
.func = function, \
Set the func member to the function parameter.
.task_list = LIST_HEAD_INIT((name).task_list), \
Initializes the list as empty. task_list points to itself.
The . notation is used through-out the kernel source and is a gcc feature (and later C99), called designated intializers. Instead of having to set all members of a structure, only the named ones are initialized with the others set to zero. This allows people to extend the structure without modifying all the declarations. It is not a c-preprocessor feature, but a 'C' language (extension).

A previously defined constant, given as macro argument, is considered as string literal

Let's say I have defined a macro which does this
#define MY_MACRO(NAME) \
std::string get##NAME() const \
{ \
return doSomething(#NAME); \
}
Where doSomething method signature will be something like this
std::string doSomething(const std::string& parameter);
This works pretty well when the NAME macro parameter has no dashes in it.
For example :
#define MY_MACRO(thisIsA_test) // Works
But, when I have a dash in my string (this can happen) it won't work because dashes are not allowed in method names
#define MY_MACRO(thisIsA-test) // does NOT WORK
I have tried to work it around this way
#define thisIsAtest "thisIsA-test"
#define MY_MACRO(thisIsAtest)
Everything compiles just fine and I have the getthisIsAtest method generated but unfortunately the macro is not resolved and "thisIsAtest" is kept as string literal.
In other words the doSomething parameter string value will be "thisIsAtest" whereas I was expecting "thisIsA-test".
To expand the macro argument, just use an indirection macro.
#define stringize_literal( x ) # x
#define stringize_expanded( x ) stringize_literal( x )
Your use-case:
return doSomething( stringize_expanded( NAME ) );
Now the method will be named with name of the macro, and the function will be called with the contents of the macro. Somewhat questionable in terms of organization, but there you have it.
Why it works:
By default, macro arguments are expanded before being substituted. So if you pass thisIsAtest to parameter NAME, the macro expansion will replace NAME with "thisIsA-test". The pre-expansion step does not apply when you use a preprocessor operator # or ## though.
In your original code, one use of NAME is subject to ## and the other is subject to # so the macro definition of thisIsAtest never gets used. I just introduced a macro stringize_expanded which introduces an artificial use of NAME (via x) which is not subject to an operator.
This is the idiomatic way to use # and ##, since the expansion is desired more often than the literal macro name. You do happen to want the default behavior for ## in this case, but it could be considered a case of poor encapsulation (as the name of an interface is used to produce output), if you wanted to apply real programming principles to the problem.
There's nothing to work around.
As you have said yourself, dashes are not valid in function names.
So, do not use them.

Capture a name in C macro

The following iterator macro is given to me (cannot change)
#define ITERATE(MACRO) \
MACRO(v1) \
MACRO(v2) \
MACRO(v3) \
MACRO(v4)
The idea behind this is that I can now define my own one-argument macro and pass it into the iterator to expand for v1, v2, v3, v4. For example:
#define MYSTUFF(X) doSth(X);
ITERATE(MYSTUFF)
will expand to
doSth(v1); doSth(v2); doSth(v3); doSth(v4);
My current problem is that I want to invoke ITERATE within another macro which would like to pass an extra argument into MYSTUFF beyond one provided by the ITERATE.
To achieve that I was hoping that I could capture the extra parameter name with the following construct:
#define PARTIAL(T) FULL(UUU,T)
#define FULL(U,V) doSth(U,V)
#define START(UUU) ITERATE(PARTIAL)
START(bla)
I was hoping that when ITERATE(PARTIAL) is expanded to:
FULL(UUU,v1) FULL(UUU,v2) FULL(UUU,v3) FULL(UUU,v4)
I will actually capture the UUU parameter of START and it will be replaced by bla. Unfortunately that is not the case (at least in gcc).
Do you know if such name capturing can be achieved differently?
Or perhaps you have a different idea how to solve the problem of passing extra parameter into MACRO?
I may be permitted to change ITERATOR definition itself but only if it doesn't break any existing code already using it.
You can't do it this way. Your START() macro basically takes a single argument, which it then discards.
What you can do is define UUU where you need it, eg.
#define PARTIAL(T) FULL(UUU,T)
#define FULL(U,V) doSth(U,V)
#define START() ITERATE(PARTIAL)
// ...
#define UUU blah
START()
#undef UUU
Your problem, simplified, looks like this:
#define FOO UUU
#define START(UUU) FOO
START(5)
Here's what happens:
macro START is encountered in line START(5)
START is a function-like macro, so it becomes expanded with argument UUU=5):
stage 1 (argument expansion): macro arguments are macro-expanded
Nothing happens, 5 is not a macro.
Body: FOO
stage 2 (argument prescan): macro arguments are substituted into the macro body.
Nothing happens, UUU is not in the body.
Body: FOO
stage 3 (expansion): the body is macro-expanded again
FOO gets expanded into UUU, which is not a macro.
Body: UUU
I can't think of any clever way to expand FOO inside the body before the argument prescan happens. I don't think it's possible to do what you want directly.
Go with #Hasturkun's workaround and make UUU a macro, not a parameter.

What does "#define STR(a) #a" do?

I'm reading the phoneME's source code. It's a FOSS JavaME implementation. It's written in C++, and I stumbled upon this:
// Makes a string of the argument (which is not macro-expanded)
#define STR(a) #a
I know C and C++, but I never read something like this. What does the # in #a do?
Also, in the same file, there's:
// Makes a string of the macro expansion of a
#define XSTR(a) STR(a)
I mean, what's the use of defining a new macro, if all it does is calling an existing macro?
The source code is in https://phoneme.dev.java.net/source/browse/phoneme/releases/phoneme_feature-mr2-rel-b23/cldc/src/vm/share/utilities/GlobalDefinitions.hpp?rev=5525&view=markup. You can find it with a CTRL+F.
In the first definition, #a means to print the macro argument as a string. This will turn, e.g. STR(foo) into "foo", but it won't do macro-expansion on its arguments.
The second definition doesn't add anything to the first, but by passing its argument to another macro, it forces full macro expansion of its argument. So XSTR(expr) creates a string of expr with all macros fully expanded.
# is the stringizing operator. The preprocessor makes a string out of the parameter.
Say you have:
STR(MyClass);
It would be preprocessed as:
"MyClass";
The level of indirection (using XSTR()) has to do with macro expansion rules.
First, you should know that this pair of macros is actually fairly common. The first does exactly what the comment says -- it turns an argument into a string by enclosing it in double quotes.
The second is used to cause macro expansion of the argument. You typically use them together something like this:
#define a value_a
printf("%s", XSTR(a));
The macro expansion will expand a out to string_a, and the stringify will turn that into a string, so the output will be value_a.
The #a is referred to as the stringizer operator. It takes the formal parameter, in this case a, and turns it in to a string by enclosing it in double quotes.
So if you have:
string s = STR("my quoted string");
cout << s;
The output would be:
"my quoted string"

Concat Macro argument with namespace

I have a macro, where one of the arguments is an enum value, which is given without specifying the namespace scope. However somewhere inside the macro I need to access it (obviously I must define the namespace there), but I can't seem to concat the namespace name with the template parameter. Given the following samplecode the compiler complains that pasting :: and Val doesnt give a valid preprocessor token (it works fine for concating get and a to getVal though).
namespace TN
{
enum Info
{
Val = 0
};
}
#define TEST(a) TN::Info get ## a(){return TN::##a;}
TEST(Val)
So is there any way to make this work without using another argument and basically specifying the value to be used twice (e.g. #define TEST(a,b) TN::Info get ## a(){return b;})?
## is a token pasting operator, i.e. it should make a single token out of multiple bits of token and as the compiler says, ::Val isn't a single token, it's two tokens.
Why do you need think you need the second ## at all? What's wrong with this.
#define TEST(a) TN::Info get ## a () { return TN::a; }
Only use ## when you want to concatenate two items and have the compiler treat the result as a single token (e.g. an identifier).
In your macro, the first use of ## is correct, as you are trying to construct an identifier by pasting together get and the contents of a, but second use of ## is spurious, as you just want to make an identifier out of the contents of a and the :: operator is a separate entity to that. GCC will complain about this (though MSVC++ copes).
#define TEST(a) TN::Info get ## a(){return TN::a;}
should work.