How to check 2 defines are the same? - c++

In MFC application, there is a define for diagnosing the memory leak and so on.
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
In afx.h, there exists DEBUG_NEW definition
void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine);
#define DEBUG_NEW new(THIS_FILE, __LINE__)
How to check new is defined as DEBUG_NEW?
I tried to use
#if defined(new) && new == DEBUG_NEW
It does not work.

If you have access to the MFC application code in question, I would change the #ifdef contruct to:
#ifdef _DEBUG
#define new DEBUG_NEW
#define NEW_REDEFINED
#endif
Then you can do your check using #ifdef NEW_REDEFINED

The idea of redefining a keyword in a macro is a somewhat crazy one and I certainly hope nobody else follows this MFC idea. In that case, a simple
#ifdef new
would suffice. If the default new is used, the keyword won't be defined as a macro.
Depending on what specifically you're after, another option might be to simply use
#ifdef _DEBUG
trusting that new is defined in the form you expect if and only if _DEBUG is defined.
But C++ does not have any check that can be performed in an #if expression that will tell you if a macro is defined in a particular form.

If you only need to know if the two definitions are the same at runtime you could use something like:
#include "string.h"
#define STR(s) #s
#define compare(a, b) (strcmp(STR(a), STR(b)) == 0)
This would compare the exact string used to define each macro, so it may only be useful in certain cases, consider:
#define MY_INT1 int
#define MY_INT2 int
#define MY_INT3 (int)
#define MY_FLOAT float
compare(MY_INT1, MY_INT2) // Evaluates to true
compare(MY_INT1, MY_INT3) // Evaluates to false
compare(MY_INT1, MY_FLOAT) // Evaluates to false

Related

How to use "else if" with the preprocessor #ifdef?

In my project the program can do one thing of two, but never both, so I decided that the best i can do for one class is to define it depending of a #define preprocessor variable. The next code can show you my idea, but you can guess that it does not work:
#ifdef CALC_MODE
typedef MyCalcClass ChosenClass;
#elifdef USER_MODE
typedef MyUserClass ChosenClass;
#else
static_assert(false, "Define CALC_MODE or USER_MODE");
#endif
So i can do
#define CALC_MODE
right before this.
I can resign the use of static_assert if needed. How to do this?
Here's a suggestion, based largely on comments posted to your question:
#if defined(CALC_MODE)
typedef MyCalcClass ChosenClass;
#elif defined(USER_MODE)
typedef MyUserClass ChosenClass;
#else
#error "Define CALC_MODE or USER_MODE"
#endif

Combining preprocessor macros and variables

In my C++ code I have to execute certain code under two conditions: because of a preprocessor macro OR a boolean variable check. For example:
bool done=false;
#ifdef _DEBUG
executeDebugCode();
done=true;
#endif
if (inputParam && !done)
executeDebugCode();
Is there a way to write the above code in a more elegant way, without repeating the executeDebugCode() function call two times?
EDIT:
the executeDebugCode() function should be executed once, and if one of the two condition is met. For example a function that should be executed in DEBUG mode only, that could be set by preprocessor macro or command line parameter.
Assuming that you want to execute this code only once, if at least one of these conditions is true:
if ( inputParam
#ifdef DEBUG
|| true
#endif
)
{
executeDebugCode();
}
The form I see most for this, and which tends to work well, is do make the exact check performed depend on _DEBUG, so you'd get:
#ifdef _DEBUG
#define SHOULD_EXECUTE_DEBUG_CODE() 1
#else
#define SHOULD_EXECUTE_DEBUG_CODE() inputParam
#endif
if (SHOULD_EXECUTE_DEBUG_CODE())
executeDebugCode();
Note that if inputParam is a local variable (as Sambuca points out in the comments), this macro SHOULD_EXECUTE_DEBUG_CODE cannot be used in other functions, and for maintainability, it may be worth adding #undef SHOULD_EXECUTE_DEBUG_CODE at the end of the function to prevent accidental misuse.
How about something like this :
bool debugEnabled = inputParam;
#ifdef _DEBUG
debugEnabled = true;
#endif
if (debugEnabled)
executeDebugCode()
ie. use one flag to control the code behavior, but allow that flag to be set in different ways.
My approach would be something like this
#ifdef _DEBUG
#define SHOULD_EXECUTE 1
#else
#define SHOULD_EXECUTE 0
#endif
if (SHOULD_EXECUTE || inputParam) {
executeDebugCode();
}
This way your if-statement shows right away that you're checking on a preprocessor define and another (boolean) condition.
This will not generate any overhead in runtime if DEBUG is not enabled.
#ifdef _DEBUG
#define MY_DEBUG true
#else
#define MY_DEBUG false
#endif
if ( inputParam || MY_DEBUG )
executeDebugCode();

Can I make a macro to execute debug or release code?

For example if I had this code:
#ifdef _DEBUG
mPluginsCfg = "plugins_d.cfg";
#else
mPluginsCfg = "plugins.cfg";
#endif
Can I define a macro that looks like
#define DEBUG_RELEASE(debug_code, release_code)
and then use it like this;
DEBUG_RELEASE(mPluginsCfg = "plugins_d.cfg";,mPluginsCfg = "plugins.cfg";)
I'm sure that it works, and I'm almost sure that it is defined to work.
#ifdef _DEBUG
#define DEBUG_RELEASE(d,r) d
#else
#define DEBUG_RELEASE(d,r) r
#endif
I'm unsure whether I've seen anything uglier in the wonderful world of preprocessor macros.

error C2661: 'CObject::operator new' : no overloaded function takes 4 arguments

I have a memory leak that I'm trying to hunt down in my mfc program. Typically I would do something like the following:
header file
// Leak Detection
#if defined(WIN32) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
cpp file
// Leak detection
#if defined(WIN32) && defined(_DEBUG) && defined(_CRTDBG_MAP_ALLOC)
#ifdef DEBUG_NEW
#undef DEBUG_NEW
#endif
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
This technique works well in most files, but when I include it in some files such as my document, I get the error: error C2661: 'CObject::operator new' : no overloaded function takes 4 arguments
What's the solution here? Should I be #undef-ing new somewhere or something?
Thanks!
I also use the same functionality as you for the purpose of leak detection.
Either you can comment out or delete the DEBUG_NEW definition block, assuming you don't need it any more for trapping memory leaks. Or if you still need it, leave it as it is and use
#ifdef _DEBUG
#undef new
CMyOject* pMyObjectInst = new CMyObject();
#define new DBG_NEW
#endif
So, you undefine new just before object creation (see the line numbers in your Error List) and redefine it again immediately after, so that any memory leaks which occur after this object creation are still identifiable.
I have similar problem caused by putting #define new DEBUG_NEW before #include ... statements in .cpp file. Changing the order resolved my problem.

What use cases necessitate #define without a token-string?

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);