Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ preprocess macro with 2 arguments

I have the following macro:

 #define LOG(level,text)

I want to define macro which includes both level and text:

#define MY_LOG_MESSAGE LEVEL1,"This is my log"

so latter I can run:

  LOG(MY_LOG_MESSAGE);

gcc issues preprocess error:

error: macro "LOG" requires 2 arguments, but only 1 given

Any ideas?

like image 405
dimba Avatar asked Aug 29 '13 12:08

dimba


3 Answers

You have to convince the preprocesor to expand the MY_LOG_MESSAGE macro before it tries to expand LOG(). This can be done by using a simple helper macro:

#define LOG1(x) LOG(x)

LOG1(MY_LOG_MESSAGE);

The arguments given to LOG1() are expanded in it's body, leading to a valid call for LOG().

like image 101
sth Avatar answered Sep 28 '22 18:09

sth


This is very similar to sth's answer, but allows using either one or two parameters:

#define LOG_(level,text) implementation
#define LOG(...) LOG_(__VA_ARGS__)

#define MY_LOG_MESSAGE LEVEL1,"This is my log"

LOG(MY_LOG_MESSAGE);
LOG(LEVEL2, "Another log");

The point is that LOG causes the parameter to be expanded before calling LOG_, thus giving it two parameters in both cases.

like image 44
ugoren Avatar answered Sep 28 '22 19:09

ugoren


If you use a define for each log message anyways, maybe do it like this:

#define LOG_MY_MESSAGE LOG(LEVEL1, "This is my log")

And use in code simply as

LOG_MY_MESSAGE

like image 31
Wutz Avatar answered Sep 28 '22 19:09

Wutz