I'm creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the value of the first variable. For instance:
#define MY_MACRO int my_variable_[random-number-here] = getCurrentTime();
The other motivation to use that is to avoid selecting certain name to the variable so that it be the same as a name eventually chosen by the developer using the macro.
Is there a way to generate random variable names inside a macro in C++?
-- Edit --
I mean unique but also random once I can use my macro twice in a block and in this case it will generate something like:
int unique_variable_name;
...
int unique_variable_name;
In this case, to be unique both variable names have to be random generated.
Try the following:
// One level of macro indirection is required in order to resolve __COUNTER__,
// and get varname1 instead of varname__COUNTER__.
#define CONCAT(a, b) CONCAT_INNER(a, b)
#define CONCAT_INNER(a, b) a ## b
#define UNIQUE_NAME(base) CONCAT(base, __COUNTER__)
void main() {
int UNIQUE_NAME(foo) = 123; // int foo0 = 123;
std::cout << foo0; // prints "123"
}
__COUNTER__ may have portability issues. If this is a problem, you can use __LINE__ instead and as long as you aren't calling the macro more than once per line or sharing the names across compilation units, you will be just fine.
use __COUNTER__ (works on gcc4.8, clang 3.5 and Intel icc v13, MSVC 2015)
#define CONCAT_(x,y) x##y
#define CONCAT(x,y) CONCAT_(x,y)
#define uniquename static bool CONCAT(sb_, __COUNTER__) = false
Add M4 to your build flow? This macro language has some stateful capabilities, and can successfully be intermingled with CPP macros. This is probably not a standard way to generate unique names in a C environment, though I've been able to sucessfully use it in such a manner.
You probably do not not want random, BTW, based on the way you posed your question. You want unique.
You could use __FILE__ and __LINE__ in the macro expansion to get you the uniqueness you seem to be going for... those metavariables get defined within the source file context, so be careful to make sure you get what you are looking for (e.g., perils of more than one macro on the same line).
Generating unique names in the preprocessor is difficult. The closest you can get is to mangle __FILE__ and __LINE__ into the symbol as popcnt suggests. If you really need to generate unique global symbol names, then I would follow his suggestion about using something like M4 or a Perl script in your build system instead.
You might not need unique names. If your macro can impose a new scope, then you can use the same name since it will simply shadow other definitions. I usually follow the common advice of wrapping macros in do { ... } while (0) loops. This only works for macros which are statements - not expressions. The macro can update variables using output parameters. For example:
#define CALC_TIME_SINCE(t0, OUT) do { \
std::time_t _tNow = std::time(NULL); \
(OUT) = _tNow - (t0); \
} while (0)
If you follow a few rules, you are usually pretty safe:
Use leading underscores or similar naming conventions for symbols defined within the macro. This will prevent problems associated with a parameter using the same symbol from occurring.
Only use the input parameters once and always surround them with parentheses. This is the only way to make macros work with expressions as input.
Use the do { ... } while (0) idiom to ensure that the macro is only used as a statement and to avoid other textual replacement problems.
Instead of having the preprocesser create a name, you could possibly let the macro user give you a name.
#define MY_MACRO(varname) int varname = getCurrentTime();
I needed something similar for a case where I didn't have any profiling tools, but I wanted to count how many threads were inside a particular block of code as well as the amount of time (ticks) spent in that block of code by each thread, In this case every block needed a unique static variable accessible to all threads, and I needed to later reference that variable to incr (I used a logging API rather than printf in the actual code, but this works as well). At first I thought I was very clever by doing the following:
#define PROF_START { \
static volatile int entry_count##___FUNCTION__##__LINE__ = 0; int *ptc = &entry_count##___FUNCTION__##__LINE__; \
clock_t start, end; \
start = times(0); \
(*ptc)++;
But then I realized this is just silly and the C compiler will simply do this for you, as long as each "static" declaration is its own block:
#include <stdio.h>
#include <sys/times.h>
#define PROF_START { \
static int entry_count = 0; \
clock_t start, end; \
start = times(0); \
entry_count++;
#define PROF_END \
end = times(0); \
printf("[%s:%d] TIMER: %ld:%d\n" , __FUNCTION__, __LINE__, end-start, entry_count); \
entry_count--; \
}
Note the open/close brackets in each macro. This isn't strictly thread-safe, but for my profiling purposes I could assume the incr and decr operations were atomic. Here's a recursion sample which uses the macros
#define ITEM_COUNT 5
struct node {
int data;
struct node *next;
};
revsort(struct node **head)
{
struct node *current = *head;
struct node *next_item;
while (current->next)
{
PROF_START
next_item = current->next;
current->next = next_item->next;
next_item->next = *head;
*head = next_item;
PROF_END
}
}
rrevsort(struct node **head)
{
struct node *current = *head;
struct node *next_item = current->next;
PROF_START
current->next = 0;
if (next_item)
{
*head = next_item;
rrevsort(head);
next_item->next = current;
}
PROF_END
}
printnode(struct node *head)
{
if (head)
{
printf("%d ", head->data);
printnode(head->next);
}
else
printf("\n");
}
main()
{
struct node node_list[ITEM_COUNT];
struct node *head = &node_list[0];
int i;
for (i=0; i < ITEM_COUNT - 1; i++)
{
PROF_START
node_list[i].data = i;
node_list[i].next = &node_list[i+1];
PROF_END
}
node_list[i].data = i;
node_list[i].next = 0;
printf("before\n");
printnode(head);
revsort(&head);
printf("after\n");
printnode(head);
rrevsort(&head);
printf("before\n");
printnode(head);
}
Extra hint, the above program is a common interview question. Excerpt from "nm -A":
macro:0804a034 b entry_count.1715
macro:0804a030 b entry_count.1739
macro:0804a028 b entry_count.1768
macro:0804a02c b entry_count.1775
Here is a succinct macro definition to generate the singleton pattern above.
#define SINGLETON_IMPLIMENTATION(CLASS_NAME) static CLASS_NAME *g##CLASS_NAME = nil; + (CLASS_NAME *)instance { #synchronized(self) { if (g##CLASS_NAME == nil) g##CLASS_NAME = [self new]; } return g##CLASS_NAME; }
#define SINGLETON_DECLARATION(CLASS_NAME) + (CLASS_NAME *)instance;
While I don't think its even possible, you should seriously consider making a class out of this.
If you want a random element in a random array to hold a certain value, you can do this:
std::vector< std::vector<int> > m_vec;
Then wrap it in a class, so the developer can only set a number:
void set(int foo)
{
m_vec[random()][random()] = foo;
}
Is there any reason why you want it a macro? Random variable name sounds dangerous, what if it picks something already defined somewhere else in the code?
Related
How can I use macros as function pointers? I have no idea to solve this. I created a sketch (doesn't work, full of syntax errors) to show what I try to accomplish. Please help!
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation
struct Pin {
CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }
Pin(CalcMethod *calcMethodParam) {
calcMethod = calcMethodParam;
}
int calc(int x) {
return calcMethod(x);
}
};
#define PIN_COUNT 2
Pin *pins[PIN_COUNT];
void start() {
pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
int pin1CalcResult=pins[1]->calc(6); // =6*1024
}
Macros are handled by the preprocessor. They don't exist in the compiled code, therefore there is no pointer.
There is one rule you should follow in modern code and that rule is "don't use macros for furnctions". Macros for functions are a relict that still has some good uses but they are very rare.
Just declare a normal function
int do_out(int x) {
return x / 1024 * 100;
}
Also see "static const" vs "#define" vs "enum"
You can, but not advisable, use macros as named lambdas. Thus
#define D0_OUT [](int x) { return x / 1024 * 100; }
#define D1_OUT [](auto x) { return x * 1024; }
and it should work.
D0_OUT example usable in C++11 and D1_OUT usable with C++14.
I know this is an old thread..
Assuming that you cannot just change the macro to be a function. Maybe it is part of a driver of library somewhere and you need to pass it into another function for some reason like unit testing. You can just wrap the macro within your .c file where you want to use it.
So this:
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
becomes:
static int D0_OUT_wrapper(int x)
{
return D0_OUT(x);
}
So wrapper goes in like normal:
pins[0] = new Pin(D0_OUT_wrapper);
If you have full control of the code you are writing then just don't use macros.
So I had this query wherein say I have an enum and a struct that look like these,
enum fields {
field_1,
field_2
};
struct my_struct {
int field_1;
int field_2;
};
My specific need is, given the enum with the names of the structure members (field_1, field_2 etc) I should be able to generate a macro which can set the structure member to a given value.
#define my_macro (__a, __field) \
__a.__field = 1;
So is there a way to call my_macro like this:
struct my_struct b;
/* extract members of enum as string literals */
my_macro(b, /*field name from the enum */);
Few other posts detailing usage of boost macros helps me extract the enum members as strings ( How to convert an enum type variable to a string?). Issue is with passing it in the appropriate manner to the macro.
It should work the way it is. Macros are processed before compilation, while the code is still code, and they result in code generation.
Your macro #define my_macro(__a, __field) __a.__field = 1; will cause any entry like my_macro(x, y) to be transformed into x.y = 1;, literally, before its handed to the compiler.
If you do something like my_macro(1+1, "test"), it will generate the code 1+1."test" = 1; and will create a compile error. Thats how simple macros are.
Thats why macro parameters are often enclosed by () to make sure it will work the way it was intented, if you don't do that things like this can happen:
#define div_by_100(a) a / 100
printf("%d\n", div_by_100(1000)); // will print 10
printf("%d\n", div_by_100(500 + 500)); // will print 505
This happens because order of operations is resolved at compile time, after the macros have been resolved.
Notice that, because macros are resolved before compilation, they are not a runtime solution. If this enum value is not explict in the code, macros won't help you at all. You will have to write a routing function that will assign a value to each member of this class/struct depending on what enum value was given. Example:
void route(struct farm* s, enum animals e)
{
switch (e)
{
case cow:
s->cow = 1;
break;
case duck:
s->duck = 1;
break;
case horse:
s->horse = 1;
break;
case goat:
s->goat = 1;
break;
}
}
It depends on the way your mechanism of turning an enum to a string works. Your macro should work as long as that mechanism is still a macro that gets replaced by the preprocessor. That's the issue. Your macro should otherwise work properly.
I am trying to generate a class given below with the help of recursive Macros/ pre-processor directives. I cannot use templates as I am building the type (a class). The macro users must be able to create this class without repeating the variables. I do not want to use containers for the variables as they can have meaningful names.
class IInterface;
class XYZ
{
int Mark1, Mark2, Mark3 /* variables to be passed */;
int count;
XYZ(IInterface * I)
{
count = 0;
// initialization values to be passed
Mark1 = 10; count++; I -> add(Mark1);
Mark2 = 20; count++; I -> add(Mark2);
Mark3 = 30; count++; I -> add(Mark3);
}
};
I am trying to put place holders and then expand them.
#define CLASS(_name) class _name {\
int VARS; \
int count; \
_name(IInterface * I) \
{ \
count = 0; \
VAR = val; count++; I -> add(VAR); \
} \
};
#define INIT // expansion code
CLASS(XYZ)
INIT(Mark1, 10) // variables should be sent only once for all the placeholders
INIT(Mark2, 20)
INIT(Mark3, 30)
How can I expand INIT to replace the placeholders?
I would like to know if this is feasible/ recommended.
This is not perhaps the "answer" directly to the question but achieves the same aim.
Macros in general are "evil" but can be useful at times. Here, however, they remain evil as anyone using the class later on will be hard-pressed to work out its actual definition, and errors will be much harder to decipher.
Therefore the recommendation is to use a scripting language as a pre-build step that can read in the configuration of your classes and generate the C++ files from it.
Then users of the classes will see actual C++ headers that look comprehensible.
Perl or Python might be used as the scripting language for this purpose. I would probably choose Perl.
You would then make this a pre-build step.
The generated headers would be the target, the scripted definition which is in a format you decide is the input, and a make script would know therefore if the targets are up-to-date.
For the input (class definition) file, you could use XML or JSON format, both of which give you nested key-value pairs with repeating groups. Whichever you choose has the advantages that
They are well known formats, understood by developers who may need to read or write them
There is already code to parse them so you won't need to write an actual parser, instead you'd just use the parsed data to generate your output file.
How can I create a typedef using a macro (#define)?
I am, for various reasons, trying to use a macro to do typedef'ing in C. Something along the lines of templates for C++.
As an example, I would expect the preprocessor to expand the #define and typedef a struct whose "content" member is of type char:
#define DEFINE_FOO_TYPE(content_type__, content_type_name__) \
typedef struct { \
content_type__ content; \
} content_type_name__
DEFINE_FOO_TYPE(char, foo_t);
foo_t foo_var;
foo_var.content = 'g';
Apparently that is not the case. Is it possible to do these sort of things in C at all, or is the only way a C++ template?
To preempt questions along the lines of "why don't you just use a C++ template?". The answer is that I'm trying to do it in C because it's fun.
Try this:
#define DEFINE_FOO_TYPE(content_type__, content_type_name__) \
typedef struct { \
content_type__ content; \
} content_type_name__
DEFINE_FOO_TYPE(char, foo_t);
int main() {
foo_t foo_var;
foo_var.content = 'g';
return 0;
}
I.e. use content_type_name__ instead of element_type_name__
Proof of compilation
I posted in a comment because I thought it was too trivial, but here it is:
Surely you are not just pasting that quoted code into gcc, are you? You can't just execute code outside any function. Put the last line inside a function.
simply put the last two lines of code into main()
or any function it will work for sure.
Is there a way to display the name of an enum's value?
say we have:
enum fuits{
APPLE,
MANGO,
ORANGE,
};
main(){
enum fruits xFruit = MANGO;
...
printf("%s",_PRINT_ENUM_STRING(xFruit));
...
}
using the preprocessor
#define _PRINT_ENUM_STRING(x) #x
won't work as we need to get the value of the variable 'x' and then convert It to string.
Is this at all possible in c/C++?
You could use the preprocessor to do this, I believe this technique is called X-Macros:
/* fruits.def */
X(APPLE)
X(MANGO)
X(ORANGE)
/* file.c */
enum fruits {
#define X(a) a,
#include "fruits.def"
#undef X
};
const char *fruit_name[] = {
#define X(a) #a,
#include "fruits.def"
#undef X
};
Note that the last entry includes a trailing comma, which is allowed in C99 (but not in C89). If that is a problem you can add sentinal values. It is also possible to make the macro more complicated by giving multiple arguments for custom names or enum values, etc:
X(APPLE, Apple, 2)
#define X(a,b,c) a = c, /* in enum */
#define X(a,b,c) [c] = #b, /* in name array */
Limitations: You cannot have negative constants and your array is sizeof (char *) * largest_constant. But you could work around both by using an extra lookup table:
int map[] = {
#define X(a,b,c) c,
#include "fruits.def"
#undef X
};
This doesn't work of course. What does work is generating an extra set of enum constants as keys for the names:
enum fruits {
#define X(a,b,c) a ## _KEY,
#include "fruits.def"
#undef X
#define X(a,b,c) a = c,
#include "fruits.def"
#undef X
};
Now you can find the name of X(PINEAPPLE, Pineapple, -40) by using fruit_name[PINEAPPLE_KEY].
People noted that they didn't like the extra include file. You don't need this extra file, you also use a #define. This may be more appropriate for small lists:
#define FRUIT_LIST X(APPLE) X(ORANGE)
And replace #include "fruits.def with FRUIT_LIST in the previous examples.
You can use a mapping in this case.
char *a[10] = { "APPLE","MANGO","ORANGE"};
printf("%s",a[xFruit]);
Yes the preprocessor won't work unless you provide the exact enum -value.
Also check this question for more insights.
I've used preprocessor programming successfully to get a macro of this kind:
DEFINE_ENUM(Fruits, (Apple)(Mango)(Orange));
It does a tad more than just printing the names, but it could easily be simplified to 2 switches if necessary.
It's based on Boost.Preprocessor facilities (notably BOOST_PP_SEQ_FOREACH) which is a must have for preprocessor programming, and I find it much more elegant than the X facility and its file reinclusion system.
public enum LDGoalProgressUpdateState
{
[Description("Yet To Start")]
YetToStart = 1,
[Description("In Progress")]
InProgress = 2,
[Description("Completed")]
Completed = 3
}
var values = (ENUMList[])Enum.GetValues(typeof(ENUMList));
var query = from name in values
select new EnumData//EnumData is a Modal or Entity
{
ID = (short)name,
Name = GetEnumDescription(name)//Description of Particular Enum Name
};
return query.ToList();
region HelperMethods
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
#endregion