I am trying to define a macro which includes a pre-processor if-statement that checks the DEBUG state in its body. Essentially, here is what I would like to achieve:
Option 1
#define MY_MACRO { \
#ifdef _DEBUG \
MyFunction(); \
#endif \
}
I know that an alternative implementation is the following:
Option 2
#ifdef _DEBUG
#define MY_MACRO MyFunction();
#else
#define MY_MACRO
#endif
So, I have two questions:
Is Option 1 above, correctly implemented? If not, what is the right way
to do it?
Is Option 2 always the preferred way to do this?
Yes, option two is the way to do this. As you probably discovered, option 1 just doesn't work. You should probably remove the trailing ; in the substitution though:
#define MY_MACRO MyFunction()
Otherwise, if someone writes:
if (condition)
MY_MACRO;
else
do_something_else();
The substitution yields:
if (condition)
MyFunction();;
else
do_something_else();
...and the two semicolons tell the compiler that an if statement terminated and was followed by an empty statement, then there's an unexpected and illegal else.
Depending on the exact situation, it may be better to have:
#define MY_MACRO() MyFunction()
So the calling code looks like:
MY_MACRO();
That's more consistent with a function call.
There is no way to have a macro expand to any kind of preprocessor directive, so option 1 just won't work. The closest you can come is to define macro that has multiple definitions depending on ifdefs, as you've done in option 2. One thing you can do is define a macro that just expands to its arguments or to nothing, depending on ifdefs:
#ifdef _DEBUG
#define IF_DEBUG(...) __VA_ARGS__
#else
#define IF_DEBUG(...)
#endif
Now you can use this macro in other macros:
#define MY_MACRO IF_DEBUG( MyFunction() )
Related
I want to define the macro, that based on some condition (existence of #define INITED, not the parameter of the macro) will return value, or generate compiler's error, like:
#error Not initialized!
I've tried (for myIdea.h):
#ifdef INITED
#define MyMacro(x) x->method(); //something with x
#else
#define MyMacro(x) #error Not initalized!
#endif
But that code generates error (not the one I wanted to) expected macro format parameter.
Note, that I don't want that code (working, but doing bit different thing):
#ifdef INITED
#define MyMacro(x) x->method(); //something with x
#else
#error Not initalized!
#endif
The code above will geneate error just when INITED won't be defined. I want to generate error only when I call to the MyMacro() AND INITED has not been yet defined.
I'm not the slave to the first code, but I want the result to work exactly the way I've described above (generate error WHEN calling macro MyMacro IF constant inited is not defined).
This is not possible. The preprocessor is just a very simple thing, it does not parse nested macros like that. The second pound (#) would not be understood as a nested macro by the preprocessor. The argument is pretty much handled as raw string.
You could however look into static assert with C++11 and on instead of your #error directive. You would be writing then something like this:
#ifdef INITED
#define MyMacro(x) x->method(); //something with x
#else
#define MyMacro(x) static_assert(false, "Not initalized!");
#endif
How should I write the below piece of code using macro function?
#ifdef LOG_ENABLED
m_logger->Log(szType,szMessage);
#endif
I have done something like mentioned below and it resulted in error:-
#define _LOG_MSG_CND_BEGIN_ #ifdef LOG_ENABLED
#define _LOG_MSG_CND_END_ #endif
#define WriteLogMessage(szType,szMessage) \
{\
_LOG_MSG_CND_BEGIN_\
m_logger->Log(szType,szMessage);\
_LOG_MSG_CND_END_\
}
Please let me know how to write macro function for the above three piece of code without any errors.
I have used inline function for the same piece of code but while debugging i saw that the inline function was not getting treated as inline function and so i want to use macro function in this case.
Inline function which i used was as mentioned below:-
inline void WriteLogMessage(LOG_LEVEL szType, LPCTSTR szMessage){
#ifdef LOG_ENABLED
m_logger->Log(szType,szMessage);
#endif
}
The standard C preprocessor is a bit of an idiot and doesn't understand much at all. You want something like this:
#if defined LOG_ENABLED
#define WriteLogMessage(szType,szMessage) m_logger->Log(szType,szMessage)
#else
#define WriteLogMessage(szType,szMessage)
#endif
Preprocessor directives need to be the first thing in a line:
#define _LOG_MSG_CND_BEGIN_
#ifdef LOG_ENABLED
#define _LOG_MSG_CND_END_
#endif
#define WriteLogMessage(szType,szMessage) \
{\
_LOG_MSG_CND_BEGIN_\
m_logger->Log(szType,szMessage);\
_LOG_MSG_CND_END_\
}
EDIT: If you want macros to be expanded to other macros, that's not possible.
I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for example this line:
#define OCSTR(X)
Just like that! What could be the use of this or better, when is this use of #define necessary?
This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32 is more likely defined on the command line, but it
could also be defined in a "config.hpp" file.) This would normally
only involve object-like macros (without an argument list or
parentheses).
The second would be a result of conditional compilation. Something
like:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
That allows writing things like:
TEST(X);
which will call the function if DEBUG is defined, and do nothing if it
isn't.
Such macro usually appears in pair and inside conditional #ifdef as:
#ifdef _DEBUG
#define OCSTR(X)
#else
#define OCSTR(X) SOME_TOKENS_HERE
#endif
Another example,
#ifdef __cplusplus
#define NAMESPACE_BEGIN(X) namespace X {
#define NAMESPACE_END }
#else
#define NAMESPACE_BEGIN(X)
#define NAMESPACE_END
#endif
One odd case that I recently dug up to answer a question turned out to be simply commentary in nature. The code in question looked like:
void CLASS functionName(){
//
//
//
}
I discovered it was just an empty #define, which the author had chosen to document that the function accessed global variables in the project:
C++ syntax: void CLASS functionName()?
So not really that different from if it said /* CLASS */, except not allowing typos like /* CLAAS */...some other small benefits perhaps (?)
I agree with every answer, but I'd like to point out a small trivial thing.
Being a C purist I've grown up with the assertion that EACH AND EVERY #define should be an expression, so, even if it's common practice using:
#define WHATEVER
and test it with
#ifdef WHATEVER
I think it's always better writing:
#define WHATEVER (1)
also #debug macros shall be expressions:
#define DEBUG (xxx) (whatever you want for debugging, value)
In this way, you are completely safe from misuse of #macros and prevents nasty problems (especially in a 10 million line C project)
This can be used when you may want to silent some function. For example in debug mode you want to print some debug statements and in production code you want to omit them:
#ifdef DEBUG
#define PRINT(X) printf("%s", X)
#else
#define PRINT(X) // <----- silently removed
#endif
Usage:
void foo ()
{
PRINT("foo() starts\n");
...
}
#define macros are simply replaced, literally, by their replacement text during preprocessing. If there is no replacement text, then ... they're replaced by nothing! So this source code:
#define FOO(x)
print(FOO(hello world));
will be preprocessed into just this:
print();
This can be useful to get rid of things you don't want, like, say, assert(). It's mainly useful in conditional situations, where under some conditions there's a non-empty body, though.
As you can see in the above responses, it can be useful when debugging your code.
#ifdef DEBUG
#define debug(msg) fputs(__FILE__ ":" (__LINE__) " - " msg, stderr)
#else
#define debug(msg)
#endif
So, when you are debugging, the function will print the line number and file name so you know if there is an error. And if you are not debugging, it will just produce no output
There are many uses for such a thing.
For example, one is for the macro to have different behavior in different builds. For example, if you want debug messages, you could have something like this:
#ifdef _DEBUG
#define DEBUG_LOG(X, ...) however_you_want_to_print_it
#else
#define DEBUG_LOG(X, ...) // nothing
#endif
Another use could be to customize your header file based on your system. This is from my mesa-implemented OpenGL header in linux:
#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */
# define GLAPIENTRY
# else
# define GLAPIENTRY __stdcall
# endif
#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
# define GLAPIENTRY __stdcall
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
# define GLAPIENTRY
#endif /* WIN32 && !CYGWIN */
#ifndef GLAPIENTRY
#define GLAPIENTRY
#endif
And used in header declarations like:
GLAPI void GLAPIENTRY glClearIndex( GLfloat c );
GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
GLAPI void GLAPIENTRY glClear( GLbitfield mask );
...
(I removed the part for GLAPI)
So you get the picture, a macro that is used in some cases and not used in other cases could be defined to something on those cases and nothing to those other cases.
Other cases could be as follows:
If the macro doesn't take parameters, it could be just to declare some case. A famous example is to guard header files. Another example would be something like this
#define USING_SOME_LIB
and later could be used like this:
#ifdef USING_SOME_LIB
...
#else
...
#endif
Could be that the macro was used at some stage to do something (for example log), but then on release the owner decided the log is not useful anymore and simply removed the contents of the macro so it becomes empty. This is not recommended though, use the method I mentioned in the very beginning of the answer.
Finally, it could be there just for more explanation, for example you can say
#define DONT_CALL_IF_LIB_NOT_INITIALIZED
and you write functions like:
void init(void);
void do_something(int x) DONT_CALL_IF_LIB_NOT_INITIALIZED;
Although this last case is a bit absurd, but it would make sense in such a case:
#define IN
#define OUT
void function(IN char *a, OUT char *b);
#include < iostream >
#define MY_CHK_DEF(flag) \
#ifdef (flag) \
std::cout<<#flag<<std::endl; \
#else \
std::cout<<#flag<<" ,flag not define"<<std::endl; \
#endif
int main()
{
MY_CHK_DEF(FLAG_1);
MY_CHK_DEF(FLAG_2);
MY_CHK_DEF(FLAG_3);
...
}
complier report:
main.cpp:3:24: error: '#' is not followed by a macro parameter
any ideas?
Thanks
You can't do it. #if, #else, and #endif must be the first tokens on the logical line. Your definition is just one logical line, so it doesn't work,
You have to do it the other way round(defining the macro for each #if/#ifdef/#else condition(if you nest you have to put a definition on each branch). You probably should define it at every logical branch or it will fail to compile when you try to adjust a rarely adjusted flag. You can #define noops like this. Note to be careful not to wrap expressions with side effects into #define 'd macros that reduce to a noop when the debug flag is on, or your program may not work right.
#define N(x)
#include < iostream >
#ifdef (flag)
#define MY_CHK_DEF(flag)
std::cout<<#flag<<std::endl;
#else
#define MY_CHK_DEF(flag) \
std::cout<<#flag<<" ,flag not define"<<std::endl;
#endif
int main()
{
MY_CHK_DEF(FLAG_1);
MY_CHK_DEF(FLAG_2);
MY_CHK_DEF(FLAG_3);
...
}
C preprocessor is single-pass and #define creates a pretty dumb replacement that isn't further processed - your MY_CHK_DEF(flag) macro inserts the #if statement inline into preprocessed code that is interpreted by C compiler and not valid C.
You can either rephrase it to be one-pass, or if you can't, run through preprocessor twice, manually - once through cpp -P and the second time through normal compilation process.
You actually can do this if you use BOOST processor header lib.. it provides a BOOST_PP_IF macro allow this type of decisions.
http://www.boost.org/doc/libs/1_53_0/libs/preprocessor/doc/ref/if.html
Is it possible to do something like this
#ifdef SOMETHING
#define foo //
#else
#define foo MyFunction
#endif
The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction.
I've seen __noop used, but I don't believe I can use that.
EDIT(s):
I don't think I can really use a macro here, because MyFunction takes a variable number of arguments.
Also, I'd like to make it so the arguments are NOT evaluated! (So doing something like commenting out the body of MyFunction doesn't really give me what I need, as the arguments will still be evaluated)
Try this:
#ifdef SOMETHING
#define foo(x)
#else
#define foo(x) MyFunction(x)
#endif
If your function has several arguments, then:
#ifdef SOMETHING
#define foo(x,y,z)
#else
#define foo(x,y,z) MyFunction(x,y,z)
#endif
If your function has a variable number of arguments, then your compiler may support so-called "variadic macros", like this:
#ifdef SOMETHING
#define foo(...)
#else
#define foo(...) MyFunction(__VA_ARGS__)
#endif
The reason which I've seen this kind of thing used in practice is to get rid of logging functions from a release build. However, see also Separate 'debug' and 'release' builds? in which people question whether you should even have different builds.
Alternatively, instead of redefining the function call as nothing, Jonathan's comment to this answer suggested doing something like the following:
#ifdef SOMETHING
#define foo(...) do { if (false) MyFunction(__VA_ARGS__) } while (0)
#else
#define foo(...) do { if (true) MyFunction(__VA_ARGS__) } while (0)
#endif
The reasoning for doing this is so that the function call is always compiled (so it won't be left with gratuitous errors like references to deleted variables), but only called when needed: see Kernighan & Pike The Practice of Programming and also the Goddard Space Flight Center programming standards.
From a debug.h file (originating from 1990, and therefore not using __VA_ARGS__):
/*
** Usage: TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
*/
#ifdef DEBUG
#define TRACE(x) db_print x
#else
#define TRACE(x) do { if (0) db_print x; } while (0)
#endif /* DEBUG */
With C99, there's no longer a need for the double parentheses trick. New code should not use it unless C89 compatibility is an issue.
Maybe an easier way to do this would be to conditionally omit the body of the function?
void MyFunction() {
#ifndef SOMETHING
<body of function>
#endif
}
Unless you specifically don't want a function call to be made at all, this seems like a clean way to achieve your goal.
Unfortunately the current C++ version doesn't support variadic macros.
However, you can do this:
#ifdef SOMETHING
#define foo
#else
#define foo(args) MyFunction args
#endif
// you call it with double parens:
foo((a, b, c));
If, in the case you don't want foo called, you define it as:
void foo() {}
any calls to foo() should be optimized way.
What about something along these lines:
#ifdef NDEBUG
#define DEBUG(STATEMENT) ((void)0)
#else
#define DEBUG(STATEMENT) (STATEMENT)
#endif
You would use it like this to log debugging messages:
DEBUG(puts("compile with -DNDEBUG and I'm gone"));
A non-generic version for formatted output with additional debugging information using C99 variadic macros and the __func__ identifier could look like this:
#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
__func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif
Here's how you'd use these macros:
Dprintf("count = %i", count);
Dputs("checkpoint passed");
Likely, you don't want to do the simple "code removal" as suggested,
because your callers will be expecting the side effects of the
arguments to happen. Here are some troublesome caller snippets that
should get you thinking:
// pre/post increment inside method call:
MyFunction(i++);
// Function call (with side effects) used as method argument:
MyFunction( StoreNewUsernameIntoDatabase(username) );
If you were to disable MyFunction by simply saying:
#define MyFunction(x)
then the side effects that the callers were expecting would go away,
and their code would break, and be quite difficult to debug. I like
the "sizeof" suggestion above, and I also like the suggestion to just
disable the body of MyFunction() via #ifdef's, although that means
that all callers get the same version of MyFunction(). From your
problem statement, I presume that's not actually what you want.
If you really need to disable MyFunction() via preprocessor defines on
a per-source-file basis, then I'd do it like this:
#ifdef SOMETHING
#define MyFunction(x) NoOp_MyFunction(x)
int NoOp_MyFunction(x) { }
#endif
You could even include the implementation of NoOp_MyFunction() inside
the source & headers for MyFunction(). You also have the flexibility
to add extra logging or debugging information in NoOp_MyFunction() as
well.
No, the C and C++ Standards say you cannot #define something to be a comment, so
#define foo //
won't work.
#ifdef SOMETHING
#define foo sizeof
#else
#define foo MyFunction
#endif
I'm assuming that foo is a printf style function? Anyways, this won't work with a zero parameter function, but if that were the case, you would already know what to do. If you really want to be anal you can use (void)sizeof but that's probably unnecessary.
I'm a little reluctant to post this answer because it's use of macro hackery can become the source of problems. However - if the calls to the function you want to have disappear are always used alone in a statement (ie., they are never part of a larger expression), then something like the following could work (and it handles varargs):
#ifdef SOMETHING
#define foo (1) ? ((void) 0) : (void)
#else
#define foo MyFunction
#endif
So if you have the line of code:
foo( "this is a %s - a++ is %d\n", "test", a++);
it will end up after the preprocessing step as either:
MyFunction( "this is a %s - a++ is %d\n", "test", a++);
or
(1) ? ((void) 0) : (void)( "this is a %s - a++ is %d\n", "test", a++);
which turns the pseudo-function's parameter list into a bunch of expressions separated by the comma operator that will never be evaluated, since the conditional always returns the ((void) 0) result.
A variant of this is something close to what ChriSW and Jonathan Leffler suggested:
#ifdef SOMETHING
#define foo if (0) MyFunction
#else
#define foo if (1) MyFunction
#endif
This is slightly different in that it does not require the compiler to support variadic macros (__VA_ARGS__).
I think this can be useful for eliminating debug trace function calls which are generally never combined into a larger expression, but beyond that I think it's a dangerous technique.
Note the potential for problems - especially if the parameters in the call produce side-effects (this is a general problem with macros - not just this hack). In the example, the a++ will be evaluated only if SOMETHING is defined in the build, otherwise it's not. So if code after the call depends on the value of a to be incremented, one of the builds has a bug.
If I remember correctly, you should be able to #define your macro to "nothing" and that will cause the compiler to ignore that call
#define foo()
foo(); // this will be ignored
What about surrounding each call to myFunction with
#ifdef SOMETHING
myFunction(...);
#endif
?