Friday, August 14, 2009

Debugging the C++ Preprocessor

I don't want to start a discussion about the good and the bad of the good old c preprocessor macros. Today a macro helped me keeping the DRY principle. I found myself repeatingly writing the following three lines:
int GetValue() const {return this->value_;}
void SetValue(const int& value) {this->value_ = value;}
__declspec(property(get = GetValue, put = SetValue)) int Value;
So why not make a makro:
#define DECLARE_PROPERTY(Type,Name,Member) \
Type Get##Name() const {return Member;} \
void Set##Name(const Type##& value) {Member = value;} \
__declspec(property(get = Get##Name, put = Set##Name)) Type Name;
The definiton would look like this:
DECLARE_PROPERTY(int, Value, this->value_)
Because I'm not writing macros too often (and this should be the case in future, too) I needed to review the preprocessor output. Here are the steps: Enable the following options for the cpp file you want to debug and compile the unit or module:
The result will be a a file with the extension .i in the source directory which contains the preprocessor expanded file. This file can be very large so it is a good idea to put a unique comment marker before (and/or after) the definition to find the result easier.
ps.: One advantage of C++/CLI is that you still have the power of the c preprocessor which I'm sometimes (not too often) missing in C#. Okay, you can kick on T4 templates but that's a different story and it's questionable if this doesn't violate the KISS principle.

No comments:

Post a Comment