How can I use the TRACE macro in non-MFC projects? - c++

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

Related

C++ Debug macro failing compile in release mode

I'm using visual studio (2019) and I have this macro:
#if _DEBUG
#define EngineLog(vars, ...) Log(vars, ##__VA_ARGS__)
#endif
My log function this wraps around is:
template<typename... args>
static void Log(args && ... inputs)
{
std::osyncstream bout(std::cout);
bout << ENGINE_TAG;
([&]() {
bout << inputs;
} (), ...);
bout << "\n";
}
Obviously this works fine when I'm in debug mode, but when I use release mode I get:
Error C3861 'EngineLog': identifier not found
I'm unsure why the compiler takes issue here, I was told it would remove the macro from the code when not defined but it seems not to be doing that.
if _DEBUG is not defined, then EngineLog is an unresolved name. You need to add a definition for the other case.
#if _DEBUG
#define EngineLog(vars, ...) Log(vars, ##__VA_ARGS__)
#else
#define EngineLog(vars, ...) (0 && Log(vars, ##__VA_ARGS__))
#endif
The syntax used here prevents any potential warnings about the variadic arguments being unused while at the same time preventing both the function from being called and its parameters being evaluated.
Looks like you need a #else preprocessor case to define out the macro call with an empty expansion:
#if _DEBUG
#define EngineLog(vars, ...) Log(vars, ##__VA_ARGS__)
#else
#define EngineLog(vars, ...)
#endif

#define real function name to __noop in Visual C++ 2013

I can do this in Visual C++ 2008 with Release (NDEBUG) setting:
debug.h
#ifdef _DEBUG
void debug_printf(const char* format, ...);
#else
#define debug_printf(format, v) __noop
#endif
debug.cpp
#include "stdafx.h" //#include "debug.h" is inside it
void debug_printf(const char* format, ...) {
//so much work here
}
but not anymore in Visual C++ 2013, I will get compile error in debug.cpp file. It seems I have to change the defining strategy in debug.h. But I wonder is there compiler setting to reenable again the old way?
Use a macro in the first case too, and let it call the actual function (which is named something different from the macro).
And in the second case, just have an empty macro body.
Use variadic macros.
Something like
#ifdef _DEBUG
# define debug_printf(fmt, ...) real_debug_printf(fmt, __VA_ARGS__)
#else
# define debug_printf(fmt, ...)
#endif
When _DEBUG is not defined, then the macro debug_printf is replaced by nothing (or rather, an empty line).

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.

Is there a neat method to output text to debugging pane?

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

how to separate debug and release mode code

During debug mode or while I am doing testing, I need to print lots of various information, so i use this method:
#ifdef TESTING
// code with lots of debugging info
#else
// clean code only
#endif // TESTING`
Is this a good method, or is there any other simple and elegant method ?
But this way, I am repeating the same code in two places and if anything is to be changed later on in the code, I have to do it in both places, which is time consuming and error prone.
Thanks.
I am using MS Visual Studio.
You could use a macro to print debug information and then in the release build, define that macro as empty.
e.g.,
#ifdef _DEBUG
#define DEBUG_PRINT(x) printf(x);
#else
#define DEBUG_PRINT(x)
#endif
Using this method, you can also add more information like
__LINE__
__FILE__
to the debug information automatically.
Write once
#ifdef _DEBUG
const bool is_debig = true;
#else
const bool is_debig = false;
#endif
and then
template<bool debug>
struct TemplateDebugHelper {
void PrintDebugInfo(const char* );
void CalcTime(...);
void OutputInfoToFile(...);
/// .....
};
// Empty inline specialization
template<>
struct TemplateDebugHelper<false> {
void PrintDebugInfo(const char* ) {} // Empty body
void CalcTime(...) {} // Empty body
void OutputInfoToFile(...) {} // Empty body
/// .....
};
typedef TemplateDebugHelper<is_debug> DebugHelper;
DebugHelper global_debug_helper;
int main()
{
global_debug_helper.PrintDebugInfo("Info"); // Works only for is_debug=true
}
Use a define like that on include headers
#ifdef TESTING
#define DEBUG_INFOS(_X_) CallYourDebugFunction(_X_ )
#else
#define DEBUG_INFOS(_X_) ((void)0)
#endif
and then use only this on your code
...
DEBUG_INFOS("infos what ever");
RestOfWork();
...
You can also use and search for the ASSERT and TRACE macros and use the DebugView from sysinternals to read the output real time from trace, or track problems with the ASSERT. ASSERT and TRACE do similar work, and you can get ideas from them.
comments: I use the TESTING declare, because I see that on the question.
Use Log4Cxx, instead of rolling your own logging. The Log4Cxx package is highly configurable, supports different levels of logging based on importance/severity, and supports multiple forms of output.
In addition, unless it is very critical code that must be super optimized, I would recommend leaving logging statements (assuming you use Log4Cxx) in your code, but simply turn down the logging level. That way, logging can be dynamically enabled, which can be incredibly helpful if one of your users experiences a hard-to-replicate bug... just direct them on how to configure a higher logging level. If you completely elide the logging from the executable, then there is no way to obtain that valuable debugging output in the field.
You could use something like boost::log setting severity level to the one you need.
void init()
{
logging::core::get()->set_filter
(
flt::attr< logging::trivial::severity_level >("Severity") >= logging::trivial::info
);
}
int main(int, char*[])
{
init();
BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
BOOST_LOG_TRIVIAL(info) << "An informational severity message";
BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
BOOST_LOG_TRIVIAL(error) << "An error severity message";
BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";
}
I think pantheios have something similar too.
I'm writing for embedded systems in C.
In my programs I'm using following macros:
#define _L log_stamp(__FILE__, __LINE__)
#define _LS(a) log_string(a)
#define _LI(a) log_long(a)
#define _LA(a,l) log_array(a,l)
#define _LH(a) log_hex(a)
#define _LC(a) log_char(a)
#define ASSERT(con) log_assert(__FILE__, __LINE__, con)
When I'm making release version, I simply switch off #define DEBUG directive and all macros become empty.
Note that it doesn't consume any CPU cycles and memory in release version.
Macros are the only way to save to log information: where the logging was done
(file and line number).
If I need this information I use:
_L;_LS("this is a log message number ");_LI(5);
otherwise without _L directive.
There is a simple way, which works with most compilers:
#ifdef TESTING
#define DPRINTF( args ) printf args
#else
#define DPRINTF( args ) ((void)0)
#endif
Next, in the source code you should use it as:
DPRINTF(("Debug: value a = %d, value b = %d\n", a, b));
The drawback is that you have to use double parentheses, but in old C and C++
standards variadic macro are not supported (only as a compiler extension).