Strange #define in Template? - c++

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.

Related

How to generate a list of all occurances of a macro?

I have some struct declarations that are marked with a COMPONENT macro. I would like to build a type list from these declarations. Given this code:
// a.hpp
COMPONENT(A) {
// struct body
};
// bc.hpp
COMPONENT(B) {
// struct body
};
COMPONENT(C) {
// struct body
};
I would like to generate a tuple that looks like this:
constexpr auto components = std::make_tuple(
Comp<A>{“A”},
Comp<B>{“B”},
Comp<C>{“C”}
);
The order of the elements in the tuple doesn’t matter. I will also have to manually include all the headers that contain COMPONENT declarations.
I could write a Python script that generates the file at build time but I would like to do this with the preprocessor if possible. I don’t think this is possible but I’ve seen people do some crazy stuff with the preprocessor so I thought I’d ask. I don’t understand macro meta programming as well as I understand template meta programming.
You can't do this with the C preprocessor itself. It is very limited, and doesn't support a full-fledged scripting language - not by a long shot.
Your two courses of action are:
Using a compiler's front-end to obtain a pre-preprocessing syntax tree (clang might let you do this; less sure about GCC)
Using a Python/Perl/bash/awk/sed script to look for uses of the macro.
Option 1 is much much more effort (unless you can adapt another, existing tool), but accurate; option 2 requires little effort, but is quite inaccurate without "reinventing the wheel" - with false positives (e.g. macro names within strings) and probably also false negatives (e.g. a macro applied within a macro, when its name is generated by concatenating identifiers).

Arduino - How to write Macro that define used pins by name and number and throw compiler error if pin is used elsewhere

I have been playing with this for the last 2 hours now. It should be simple but it does not work. I am not really familiar with macros and I never used them really because of their known instability. But in this case... I don't see any other better way to not use any chip memory.
What I want is not to use memory on chip for this so I choose precompiler directives, especially macros. The macro just have to define stuff, not return anything. I want that macro to be equivalent to this code :
#define PIN3 = 13;
#define PINLED = 13;
And it should be called like that :
P(13,LED);
So that way I can reference PINLED in my code and get a compiler error if any other library or code I use happens to use PIN13 when I put the P(13,LED) in the top of all the files that uses this pin in my project. I want something that names all pins the same way.
I want the 2 constants/defines to be "defined" so PIN13 cause a compiler error, but PINLED might be named different in many projects
I have tried this :
#define P(no_,name_) \
if (true) { \
PIN##name_ = no_; \
PIN##no_ = no_; \
}\
else true
This works but does only 1 define instead of 2 :
#define P(no_,name_) PIN##name_ = no_
This was suggested by many as the correct syntax. I also tried with the do... while(0) syntax and other tricks so I can use the macro as a function with a ; after it but is does not work and always throws some error.
I am using the Ino project to build because I cannot live with the arduino IDE which is pure crap compared to other IDEs.
Sorry, but your question is hardly understandable. You say you want to check whether a pin has already been used in another part of the project, and in the same time you're showing code for defining macros in macros.
But that's where it hurts, like #graben showed, it's simply not possible to achieve in C. First of all both of your syntaxes are wrong:
#define P(no_,name_) PIN##name_ = no_
you're not creating a macro name PINLED to which you assign 13, but you're assigning to the C variable PINLED the value 13. To make your PIN definition macro work, you'll need to use const int variables, which usually are easily optimized by the compiler.
Now, to get to the goal you say you want to achieve, I think it's very unlikely you can do it in macro processor code, at least in an elegant way...
And I don't think that's even necessary!
If you design well your libraries, you should not be using the pin number throughout your code and libraries, but design them so you define pins for each library at the library initialization stage. That's why usually Arduino libraries work in three steps:
allocate the memory (which is done by calling the constructor, which is often made in the included header file as a global object) ;
configure the instance (which is done with the .begin() method)
use the instance
so basically, if you have all your pins defined in the same file, you should not run into pin reuse elsewhere in your code.

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.

Why use #define instead of a variable

What is the point of #define in C++? I've only seen examples where it's used in place of a "magic number" but I don't see the point in just giving that value to a variable instead.
The #define is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++) all the time, you can do the following:
#define fori10 for (int i=0; i<=10; i++)
// some code...
fori10 {
// do stuff to i
}
If you want something more generic, you can create preprocessor macros:
#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
// do more stuff to i
}
It's also very useful for conditional compilation (the other major use for #define) if you only want certain code used in some particular build:
// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif
Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp), but you can also just put a define in your code like so:
#define DEBUG
Some resources:
Wikipedia article
C++ specific site
Documentation on GCC's preprocessor
Microsoft reference
C specific site (I don't think it's different from the C++ version though)
Mostly stylistic these days. When C was young, there was no such thing as a const variable. So if you used a variable instead of a #define, you had no guarantee that somebody somewhere wouldn't change the value of it, causing havoc throughout your program.
In the old days, FORTRAN passed even constants to subroutines by reference, and it was possible (and headache inducing) to change the value of a constant like '2' to be something different. One time, this happened in a program I was working on, and the only hint we had that something was wrong was we'd get an ABEND (abnormal end) when the program hit the STOP 999 that was supposed to end it normally.
I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.
Like this:
int Marylyn[256], Ann[1024];
The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:
#define TWO_FIFTY_SIX 256
#define TEN_TWENTY_FOUR 1024
int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];
On the following Monday afternoon I was called in and accused of having passive defiant tendencies.
#define can accomplish some jobs that normal C++ cannot, like guarding headers and other tasks. However, it definitely should not be used as a magic number- a static const should be used instead.
C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.
Most common use (other than to declare constants) is an include guard.
Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)
Here are a couple examples that use define which cannot be replaced by a variable:
#define min(i, j) (((i) < (j)) ? (i) : (j))
note this is evaluated by the pre-processor, not during runtime
http://msdn.microsoft.com/en-us/library/8fskxacy.aspx
The #define allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.
// File: MyFile.h
// This header will compile to size-zero.
#define TAX_RATE 0.625
// NO: static const double TAX_RATE = 0.625;
// NO: extern const double TAX_RATE; // WHAT IS THE VALUE?
EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.

C++ Preprocessor metaprogramming: obtaining an unique value?

I'm exploiting the behavior of the constructors of C++ global variables to run code at startup in a simple manner. It's a very easy concept but a little difficult to explain so let me just paste the code:
struct _LuaVariableRegistration
{
template<class T>
_LuaVariableRegistration(const char* lua_name, const T& c_name) {
/* ... This code will be ran at startup; it temporarily saves lua_name and c_name in a std::map and when Lua is loaded it will register all temporarily global variables in Lua. */
}
};
However manually instantiating that super ugly class every time one wants to register a Lua global variable is cumbersome; that's why I created the following macro:
#define LUA_GLOBAL(lua_name, c_name) static Snow::_LuaVariableRegistration _____LuaGlobal ## c_name (lua_name, c_name);
So all you have to do is put that in the global scope of a cpp file and everything works perfectly:
LUA_GLOBAL("LuaIsCool", true);
There you go! Now in Lua LuaIsCool will be a variable initialized to true!
But, here is the problem:
LUA_GLOBAL("ACCESS_NONE", Access::None);
Which becomes:
static Snow::_LuaVariableRegistration _____LuaGlobalAccess::None ("ACCESS_NONE", &Access::None);
:((
I need to concatenate c_name in the macro or it will complain about two variables with the same name; I tried replacing it with __LINE__ but it actually becomes _____LuaGlobalAccess__LINE__ (ie it doesn't get replaced).
So, is there a way to somehow obtain an unique string, or any other workaround?
PS: Yes I know names that begin with _ are reserved; I use them anyway for purposes like this being careful to pick names that the standard library is extremely unlikely to ever use. Additionally they are in a namespace.
You need to add an extra layer of macros to make the preprocessor do the right thing:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ...
Some compilers also support the __COUNTER__ macro, which expands to a new, unique integer every time it is evaluated, so you can use that in place of __LINE__ to generate unique identifiers. I'm not sure if it's valid ISO C, although gcc accepts its use with the -ansi -pedantic options.