I would like to display some log messages when debugging. One option is to use the very ugly
#ifdef DEBUG
std::cout << "I'm in debug mode!\n";
#endif
In the JUCE library, there is a nice macro that outputs text to the debugging pane
DBG("I'm in debug mode!")
The juce solution also allows you to do neat stuff like the following that would be desirable
int x = 4;
DBG(String("x=") + String(x))
I would like to know if a similarly neat method exists in std:: or boost::
Why not just write your own:
#ifdef DEBUG
#define DBG(x) std::cout << x;
#else
#define DBG(x)
#endif
For namespaces
namespace DBG
{
inline void DBG(const char* x)
{
#ifdef DEBUG
std::cout << x;
#endif
}
}
If you want something like printf, you should use a bit another macros:
void DebugPrintLn(const char* format, ...);
inline void Nothing(...) {}
#ifdef DEBUG
#define DBG DebugPrintLn
#else
#define DBG Nothing // Or __noop on Visual C++
#endif
Using Nothing is portable, but arguments still computed (__noop guarantees that any of argument will be not computed, VC++ specific). Better if you can use macros variable arguments (both available on GCC and latest VC++): you may even skip any argument computation in portable way:
#ifdef DEBUG
#define DBG(...) DebugPrintLn(__VAR_ARGS__)
#else
#define DBG(...) ((void)0)
#endif
In any case, you use it the same way:
DBG("Lucky day: %s %i", "Friday", 13);
I have also written my own portable TRACE macro. I share it here:
#ifdef ENABLE_TRACE
# ifdef _MSC_VER
# include <windows.h>
# include <sstream>
# define TRACE(x) \
do { std::stringstream s; s << (x); \
OutputDebugString(s.str().c_str()); \
} while(0)
# else
# include <iostream>
# define TRACE(x) std::clog << (x)
# endif // or std::cerr << (x) << std::flush
#else
# define TRACE(x)
#endif
example:
#define ENABLE_TRACE //can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"
int main (void)
{
int v1 = 123;
double v2 = 456.789;
TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}
Any improvements/suggestions/contributions are welcome ;-)
Related
#define idebug(...) \
\#ifdef _DEBUG\
printf(__VA_ARGS__);\
\#endif\
#endif
It is difficult to describe the intention,
which generally means that i predefine a macros idebug which to save some code.
If _ DEBUG flag is predefined, then print the output.
Or pretend nothing happened.
if we achieve it using a function ,it will look like this:
void idebug(...)
{
#ifdef _DEBUG
printf(...);
#endif
}
Suppose there is a program
int main()
{
int a = 10;
idebug("a:%d\n",a);
}
when we are in the debugging phase, we want a output by complier:
int main()
{
int a = 10;
printf("a:%d\n",a);
}
if we are in the release phase, we want a output by complier:
int main()
{
int a = 10;
}
Do it the other way:
#ifdef _DEBUG
# define idebug(...) printf(__VA_ARGS__)
#else
# define idebug(...) ((void)0)
#endif
When I compile and execute thes code, I get...
_DEBUG IS NOT defined
Why isn't the constant being shown as defined?
using namespace std;
int main() {
const bool _DEBUG = true;
#if defined _DEBUG
std::cout << "_DEBUG IS defined\n";
#else
std::cout << "_DEBUG IS NOT defined\n";
#endif // _DEBUG
}
#define _DEBUG
or
#define _DEBUG 1
The second method can be checked with #ifdef _DEBUG or #if _DEBUG. Usually _DEBUG is defined in compiler IDE profile.
#if defined TOKEN only checks if TOKEN is defined as a preprocessor macro, i.e. with #define TOKEN .... Here you have defined it as a (constant) variable, which is not the same thing.
const bool _DEBUG = true; defines a constant which is known to the compiler and not to the preprocessor.
The following check is executed by the preprocessor before the compiler kicks in, therefore it never sees _DEBUG constant.
#if defined _DEBUG
std::cout << "_DEBUG IS defined\n";
#else
std::cout << "_DEBUG IS NOT defined\n";
#endif // _DEBUG
To get rid of the issue, you should #define _DEBUG so that the preprocessor knows about the token.
Is it possible to disable chunks of code with c/c++ preprocessor depending on some definition, without instrumenting code with #ifdef #endif?
// if ENABLE_TEST_SONAR is not defined, test code will be eliminated by preprocessor
TEST_BEGIN(SONAR)
uint8_t sonar_range = get_sonar_measurement(i);
TEST_ASSERT(sonar_range < 300)
TEST_ASSERT(sonar_range > 100)
TEST_END
Functionally equivalent to something as follows:
#ifdef TEST_SONAR
serial_print("test_case sonar:\r\n");
uint8_t sonar_range = get_sonar_measurement(i);
serial_print(" test sonar_range < 300:%d\r\n", sonar_range < 300);
serial_print(" test sonar_range > 100:%d\r\n", sonar_range > 100);
#endif TEST_SONAR
Multiple lines can be disabled only with #ifdef or #if but single lines can be disabled with a macro. Note that multiple lines can be combined with \
#ifdef DOIT
#define MYMACRO(x) \
some code \
more code \
even more \
#else
#define MYMACRO(x)
#endif
Then when you call MYMACRO anplace that code will either be included or not based on whether DOIT is defined
That's the closest you can come and is used frequently for debugging code
EDIT: On a whim I tried the following and it seems to work (in MSVC++ and g++):
#define DOIT
#ifdef DOIT
#define MYMACRO(x) x
#else
#define MYMACRO(x)
#endif
void foo(int, int, int)
{
}
int main(int, char **)
{
int x = 7;
MYMACRO(
if (x)
return 27;
for (int i = 0; i < 10; ++i)
foo(1, 2, 3);
)
}
No, the only way to disable sections of codes effectively using preprocessing is by #ifdef #endif. Theoretically, you could use #if identifier, but it's better to stick to checking whether a variable is defined.
Another option (perhaps) is to use a preprocessing macro:
Edit:
Perhaps using plain functions and #ifdef might work better?
function test_function() {
/* Do whatever test */
}
#define TESTING_IDENTIFIER
#define TEST( i, f ) if ((i)) do { f } while (0)
Then, for each test, you define a unique identifier and call it by providing the identifier first and the function (with parenthesis) second.
TEST( TESTING_IDENTIFIER, test_function() );
Finally, f can be anything that's syntactically correct -- You don't have to create a function for every test, you can put the code inline.
I will anyway mention an obvious solution of
#define DO_TEST_SONAR
#ifdef DO_TEST_SONAR
#define TEST_SONAR if(true) {
#else
#define TEST_SONAR if(false) {
#endif
#define TEST_SONAR_END }
...
TEST_SONAR
code
TEST_SONAR_END
The code will still get compiled, not completely removed, but some smart compilers might optimize it out.
UPD: just tested and
#include <iostream>
using namespace std;
//#define DO_TEST_SONAR
#ifdef DO_TEST_SONAR
#define TEST_SONAR if(true) {
#else
#define TEST_SONAR if(false) {
#endif
#define TEST_SONAR_END }
int main() {
TEST_SONAR
cout << "abc" << endl;
TEST_SONAR_END
}
produces absolutely identical binaries with cout line commented out and non commented, so indeed the code is stripped. Using g++ 4.9.2 with -O2.
I am trying to do something like this
#define VB_S #ifdef VERBOSE
#define VB_E #endif
so that in the code instead of writing
#ifdef VERBOSE
cout << "XYZ" << endl;
#endif
I can write
VB_S
cout << "XYZ" << endl;
VB_E
This gives me a compile time error: Stray '#' in the program.
Can anyone put light on what is the right way to do this
You can't put directives inside macros. (# inside a macro as another signification -- it is the stringizing operator and must be followed by a parameter id -- but the restriction is older than that meaning)
You could do something like this:
#ifdef VERBOSE
#define VB(x) x
#else
#define VB(x) do { } while (false)
#endif
VB(cout << "foo");
Similar to Erik's response:
#ifdef VERBOSE
#define VB(...) __VA_ARGS__
#else
#define VB(...) /* nothing */
#endif
Using a variadic macro has the benefit of allowing commas inside the VB() call. Also, AFAIK, you can remove the do...while.
I prefer the following:
#define VERBOSE 1
// or 0, obviously
if (VERBOSE)
{
// Debug implementation
}
This is a little more readable since VB_S doesn't mean anything to the average user, but if (VERBOSE) does.
I want to use the TRACE() macro to get output in the debug window in Visual Studio 2005 in a non-MFC C++ project, but which additional header or library is needed?
Is there a way of putting messages in the debug output window and how can I do that?
Build your own.
trace.cpp:
#ifdef _DEBUG
bool _trace(TCHAR *format, ...)
{
TCHAR buffer[1000];
va_list argptr;
va_start(argptr, format);
wvsprintf(buffer, format, argptr);
va_end(argptr);
OutputDebugString(buffer);
return true;
}
#endif
trace.h:
#include <windows.h>
#ifdef _DEBUG
bool _trace(TCHAR *format, ...);
#define TRACE _trace
#else
#define TRACE false && _trace
#endif
then just #include "trace.h" and you're all set.
Disclaimer: I just copy/pasted this code from a personal project and took out some project specific stuff, but there's no reason it shouldn't work. ;-)
If you use ATL you can try ATLTRACE.
TRACE is defined in afx.h as (at least in vs 2008):
// extern ATL::CTrace TRACE;
#define TRACE ATLTRACE
And ATLTRACE can be found in atltrace.h
You can try the DebugOutputString function. TRACE is only enabled in debug builds.
Thanks to these answers I have fixed my bug :-)
Here I share my TRACE macro in C++ based on ideas from Ferruccio and enthusiasticgeek.
#ifdef ENABLE_TRACE
# ifdef _MSC_VER
# include <windows.h>
# include <sstream>
# define TRACE(x) \
do { std::stringstream s; s << (x); \
OutputDebugString(s.str().c_str()); \
} while(0)
# else
# include <iostream>
# define TRACE(x) std::clog << (x)
# endif // or std::cerr << (x) << std::flush
#else
# define TRACE(x)
#endif
example:
#define ENABLE_TRACE //can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"
int main (void)
{
int v1 = 123;
double v2 = 456.789;
TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}
Any improvements/suggestions/contributions are welcome ;-)
In my understanding wvsprintf has problem with formatting. Use _vsnprintf (or thcar version _vsntprintf ) instead
I've seen the following on the 'net:
#define TRACE printf
Developing this a little bit, came up with the following:
#ifdef _DEBUG
#define TRACE printf
#else
#define TRACE
#endif