Structure of #define Macro - c++

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).

Related

multiple lines macro in C

does anyone know why this is syntactically wrong?
Im trying to covert this
#define OUTS_FROM_FP(_fp, _argCount) ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
to this
#define OUTS_FROM_FP(_fp, _argCount) {\
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
}
outs = OUTS_FROM_FP(fp, vsrc1); --this is how it is being called
I get a lot of errors when running this: they start from statements that say that variables that were passed to the macro before are unused
Expanded, the original macro will look like this:
outs = ((u4*) ((u1*)SAVEAREA_FROM_FP(fp) - sizeof(u4) * (vsrc)));
That's (as far as I can tell as you didn't provide much context) valid code.
Your modified macro expands the same statement to this:
outs = { /* ... */ };
Your compiler gets all kinds of confused as you are attempting to assign a code block to a variable...
All the usual caveats regarding the use of macros in general aside, you could use the comma operator to get your modified macro "working":
#define OUTS_FROM_FP( _fp, _argCount ) \
cout << "Hello world\n", \
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
(The output is put first, as statements separated by the comma operator evaluate to the result of the last statement -- putting the output first makes the macro still evaluate to the same value as the original macro.)
All in all, you're probably better off turning that macro into a function.
Assuming that _fp and _argCount are variables or simple expressions, the original version is an expression of type u4*.
The second is more complicated. The braces make it a block, but syntactically you’re using it as an expression. This is not allowed in the C++ standard, but is supported by g++ and some other compilers. Since you say you’re using GCC, the value of this expression is the value of the last line of the block, which in this case is cout<<"Hello World"<<endl. If you were using a compiler which did not support statement expressions, you’d get a more confused syntax error.
I expect that unless you can convert an ostream to a u4 pointer (which, given what context we have, seems very unlikely), this won’t work. In this simple case, you can fix it by simply switching the order of the lines in the block. In a more complicated case, which I expect is the end goal, you probably would need to do something like
#define OUTS_FROM_FP(_fp, _argCount) {\
u4* result = ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
result; \
}
This saves the output of the macro to a temporary variable, does whatever calculations you want (which can change result), and then on the last line “returns” result outside the macro. This is less portable than DevSolar’s solution, but it works better if you need to create temporary variables, and in my opinion is more readable.
However, as others point out in the comments, there is little reason (at least that we can see) to keep this as a macro instead of converting it to a function. Functions are much more robust in a variety of ways. Reasons you might still want to keep it as a macro include the definition of SAVEAREA_FROM_FP changing or the types u4 and u1 being different in different places. Neither of these would not be good programming practice, but you can’t control what others have done before and I don’t know enough about Dalvik to say it isn’t the case.

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.

C++ preprocessor/macro to automatically add lines after function definition

In C++ I want to make functions that when declared, gets automatically added to a map( or vector, doesn't really matter in this case) as a function pointer and is called later automatically. For example this would be useful if I am writing unit test framework and I just want users to declare each of their unit tests like this:
UNIT_TEST_FUNCTION(function_name){
// do something
}
and instead something like this gets called
void function_name(){
//do something
}
int temp = register_function("function_name", function_name);
Where register_function() adds the user defined function in a map of function pointers for example. So basically, I need a mechanism that adds additional lines of code after a function definition, so that some action is performed automatically on the defined function. Is this possible using macros perhaps?
A macro can only generate a consecutive block of text. It can't lay things out the way you show in the question.
However if you're willing to rearrange a little, it can be done.
#define UNIT_TEST_FUNCTION(function_name) \
void function_name(); // forward declaration \
int temp##function_name = register_function(#function_name, function_name); \
void function_name()
A single preprocessor macro can't do what you want because it can only generate a single, contiguous block of text. Preprocessor macros are stupid in the sense that they don't understand anything about the language -- hence the preprocessor in 'preprocessor macro'.
What you can do is use a pair of macros or tuple of macros to delimit the begin and end of your test case mapping, and a single macro for each individual test case. Something along these lines:
TEST_CASES_BEGIN
UNIT_TEST_FUNCTION(function_name){
// do something
}
TEST_CASES_END
The Boost unit test facility uses a mechanism very similar to this. You might even (eventually) find this design to be a little more expressive than the design you are trying to achieve.

Strange #define in Template?

I've got a small bit of code from a library that does this:
#define VMMLIB_ALIGN( var ) var
template< size_t M, typename T = float >
class vector
{
...
private:
// storage
VMMLIB_ALIGN( T array[ M ] );
};
And you can call it by doing
//(vector<float> myVector)
myVector.array;
No parenthesis or anything.
what?
After reading the answers, it appears I should've done more looking. XCode's "Jump to Definition" gave me only one result. Searching the library gave me another:
#ifndef VMMLIB_CUSTOM_CONFIG
# ifndef NDEBUG
# define VMMLIB_SAFE_ACCESSORS
# endif
# define VMMLIB_THROW_EXCEPTIONS
# ifdef VMMLIB_DONT_FORCE_ALIGNMENT
# define VMMLIB_ALIGN( var ) var
# else
# ifdef __GNUC__
# define VMMLIB_ALIGN( var ) var __attribute__((aligned(16)))
# elif defined WIN32
# define VMMLIB_ALIGN( var ) __declspec (align (16)) var
# else
# error "Alignment macro undefined"
# endif
# endif
#endif
This offers different settings, depending on what system it's building for.
Regardless, thanks. Can't believe I got confused over a member access!
Ultimately, myVector.array refers to the array variable in the class, and variables don't need the function-calling notation ().
BTW / all-capital identifiers should only be used for preprocessor macros (as they are here). In this case, the macro VMMLIB_ALIGN must be being used to make it easier to later "enchance" the code generated for and alongside the array variable (e.g. prefixing it with static, extern, const, volatile or something compiler-specific) and/or adding some associated functionality such as get/set/search/clear/serialise functions that work on the array.
In general - when you're not sure what the macro is doing, you can get more insight by running the compiler with a command-line switch requesting preprocessor output (in GNU g++, the switch is -E)... then you'll be able to see the actual source code that the C++ compiler proper deals with.
EDIT - few thoughts re your comment, but too long to include in a comment of my own...
C++ classes are private until another access specifier is provided (but in practice the public interface is normally put first so the programmer still must remember to explicitly use private). structs are public by default. So, data is effectively exposed by default in the most common coding style. And, it doesn't need functional-call semantics to access it. Objective-C may well be better at this... your comment implies you use functional call notation for data members and functions, which is hidden by default? It's so good to have a common notation! In C++, the difficult case is where you have something like...
struct Point
{
double x, y;
};
...
// client usage:
this_point.x += 3 - that_point.y;
...then want to change to...
struct Point
{
double angle, distance;
};
...you'd need some pretty fancy and verbose manually-coded and not terribly efficient proxy objects x and y to allow the old client code to keep working unmodified while calculating x and y on the fly, and updating angle and distance as necessary. A unified notation is wonderful - allowing implementation to vary without changes to client source code (though clients would need to recompile).
maybe I'm oversimplying, but if you look at the #define macro it just writes the variable into the class.
So you have
class vector
{
...
T array[ M ];
};
after the expansion. So it's just a public variable on your class.
array is not a method, it's an array of type T of size M.
First, for the record, templates have nothing to do with this. There is no special interaction between the macro and the fact that your class is a template.
Second, going by the name of the macro, I'd guess it is meant to ensure alignment of a variable.
That is, to get an aligned instance x of a type X, you'd use VMMLIB_ALIGN(X x);
In practice, the macro does nothing at all. It simply inserts its argument, so the above results in the code X x; and nothing else.
However, it may be that the macro is defined differently depending on the hardware platform (since alignment requirements may vary between platforms), or over time (use a dummy placeholder implementation like this early on, and then replace it with the "real" implementation later)
However, it does seem pointless since the compiler already ensures natural alignment for all variables.

Macro expansion in 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.