Is there a TRACE statement for basic win32 C++? - c++

In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?

_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873

From the msdn docs, Macros for Reporting:
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.

There is also OutputDebugString. However that will not be removed when compiling release.

Trace macros that provide messages with source code link, run-time callstack information, and function prototype information with parameter values:
Extended Trace: Trace macros for Win32

I just use something like this (from memory, not tested at all...)
#define TRACE(msg) {\
std::ostringstream ss; \
ss << msg << "\n"; \
OutputDebugString(msg.str()); \
}
And then I can write things like :-
TRACE("MyClass::MyFunction returned " << value << " with data=" << some.data);
You can wrap that in some #ifdefs to remove it in release builds easily enough.

I found that using the _RPT() macro will also work with a C source file in Visual Studio 2005. This article Debugging with Visual Studio 2005/2008: Logging and Tracing provides an overview of TRACE, _RPT, and other logging type macros.
I generate a line for a log file called the ASSRTLOG which contains logs and when writing the log to the file, I also do the following source code line:
_RPT1(_CRT_WARN, "ASSRTLOG: %s", szLog1);
This line puts the same log that is going into the log file into the output window of the Visual Studio 2005 IDE.
You might be interested in the mechanics behind the approach we are using for logging. We have a function PifLogAbort() which accepts a series of arguments that are then used to generate a log. These arguments include the name of the file where the log is being generated along with the line number. The macro looks like this:
#define NHPOS_ASSERT_TEXT(x, txt) if (!(x)) { PifLogAbort( (UCHAR *) #x , (UCHAR *) __FILE__ , (UCHAR *) txt , __LINE__ );}
and the function prototype for PifLogAbort() look like this:
PifLogNoAbort(UCHAR *lpCondition, UCHAR *lpFilename, UCHAR *lpFunctionname, ULONG ulLineNo)
and to use the macro we will insert a line like this:
NHPOS_ASSERT_TEXT(sBRetCode >= 0, "CliEtkTimeIn(): EtkTimeIn() returned error");
What this macro will do is that if the return code is less than 0 (the assertion fails), a log will be generated with the provided text. The log includes the condition that generated the log along with file name and line number.
The function PifLogAbort() generates logs with a specified length and treats the output file as a circular buffer. The logs have a time and date stamp as well.
In those cases where we want to generate the descriptive text dynamically at run time, perhaps to provide the actual error code value, we use the sprintf() function with a buffer as in the following code sequence:
if (sErrorSave != STUB_BM_DOWN) {
char xBuff[128];
sprintf(xBuff, "CstSendBMasterFH: CstComReadStatus() - 0x%x, sError = %d", usCstComReadStatus, CliMsg.sError);
NHPOS_ASSERT_TEXT((sErrorSave == STUB_BM_DOWN), xBuff);
}
If we want the logs to not be generated, all we need to do is to go to the single header file where the macro is defined and define it to be nothing then recompile. However we have found that these logs can be very valuable when investigating field issues and are especially useful during integration testing.

Windows Events are a potential replacement for TRACE macros, depending on your particular scenario. The code gets compiled into both Debug and Release configurations. Event tracing can then be dynamically enabled and disabled, displayed in real-time, or dumped on a client's machine for later diagnosis. The traces can be correlated with trace information gathered from other parts of the OS as well.
If you merely need to dump information whenever code reaches certain checkpoints, together with variable content, stack traces, or caller names, Visual Studio's Tracepoints are a non-intrusive option to do so.

Related

Where can I see ATLTRACE output?

I'm maintaining a C++ COM project. There are some trace lines like ATLTRACE(message);
I searched ATLTRACE. MSDN told Visual C++ output window will display it. However, the product is a release one. The customer won't have the source nor to debug it in VS. So is there any other convenient way to see it? Will Windows Event viewer catch that? Or I have to change the code? Win7, VS2013
The ATLTRACE only uses only the debug output and it works only in the Debug version!
So you may give the enduser a debug version for testing purpose, and use DebugView from Sysinternals. But this may be complicated because you also have to over the debug runtimes that are not redistributable.
But you can easily write your own MY_TRACE macro that has the same functionality.
#define MY_TRACE GetMyTracer() // returns object of CMyTracer
...
class CMyTracer
{
...
// Helper operator to get the trace commands. They call the TraceV functions
void operator()(PCSTR pszFormat, ...);
void operator()(PCWSTR pszFormat, ...);
// Worker functions that do the real job calling TraceV functions
void Trace(PCSTR pszFormat, ...);
void Trace(PCWSTR pszFormat, ...);
// Allowed to be virtual to do some internal mystique stuff, like redirecting and this functions perform all output...
virtual void TraceV(PCSTR pszFormat, va_list args);
virtual void TraceV(PCWSTR pszFormat, va_list args);
...
Now you can use this instead of ATLTRACE
...
MYTRACE("Simple output\n");
MYTRACE("More complex output %d\n", 4711);
Note: It is not wise to replace all ATLTRACE macros with your own replacement. You may spread your trace output onto locations were it don't have impact un speed, but is worth the information.
ATLTRACE is a macro that compiles to nothing in a release build. You'll need to rebuild the project with the _DEBUG macro defined (see <atltrace.h>) to get those to display. However, output generated by ATLTRACE is a debug output string, and will typically only display in the debugger's output window.
If there is important information you need, and if it is in code you control, you'll be better off changing the ATLTRACE macro usage to something else, to either log to the event log or a log file the customer can send to you.
As mentioned by 1201ProgramAlarm, release builds of ATL projects have ATLTRACE macros evaluated to nothing and the binary has no real code generated for respective source code lines. That is, you cannot see the output without altering source code.
In order to not alter the project much, you can redefine the tracing macro itself and produce release build with tracing capabilities where output is routed as defined by you, for example to standard debug output using OutputDebugString API.
See:
How to enable the TRACE macro in Release mode?
AtlReleaseTrace

How do I use _DEBUG_ERROR in my own code?

Inside the <vector> header, there is code like this:
_DEBUG_ERROR("vector iterator not dereferencable");
_SCL_SECURE_OUT_OF_RANGE;
Which halts the program with a message and gives the programmer a chance to debug the code.
For a little toy project, I want to use _DEBUG_ERROR myself. It is defined in <xutility>.
However, when I include <xutility> and try to use _DEBUG_ERROR, I get the following error:
error C3861: "_Debug_message": identifier not found.
But _Debug_message is defined inside <xutility>, in line 28! Why does the compiler complain?
Also, is there another (maybe even somewhat portable?) way to halt the program for debugging?
Not 100% certain but I'm fairly sure it's actually std::_Debug_message. And PlasmaHH is right: assert() is the normal solution. You can write assert(!"message") to get a custom message. (Note the !)
You can use ASSERT or _ASSERT macro for assert-and-debug. Or, you can craft your own assert-macro. Use the definition of _ASSERT (taken from crtdbg.h):
#define _ASSERT_EXPR(expr, msg) \
(void) ((!!(expr)) || \
(1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, NULL, L"%s", msg)) || \
(_CrtDbgBreak(), 0))
The important function here is _CrtDbgReportW, which will display the assertion dialog-box having three standard buttons (Abort, Retry and Ignore). Depending on return value you can then call other functions. In the macro given above, function _CrtDbgBreak is called when user hits 'Retry' button (which causes function to return 1, see MSDN).
You may write to a log file, display to debug output window (using OutputDebugString), or do things you may like.

Printing output on the Output Window in Visual C++ IDE

How do I print on the output window in Visual C++? The project that I am working on isn't of a console window project type. That's when I build and run it, it doesn't open a console window. Instead, it opens a win32 application, which isn't built by me. I am just adding things to it.
I am pretty new to C++ and because I couldn't print variables out on any console, it makes it very hard for me to debug.
Since the Visual Studio 2010 project doesn't launch console when I build and run it, can I still print outputs such as variables and others on the Output window of the IDE?
Thanks for any help.
You can use OutputDebugString("..."); to print to the Output window of Visual Studio. You have to #include <windows.h> though.
I have written a portable TRACE macro.
On MS-Windows, it is based on OutputDebugString as indicated by other answers.
Here I share my work:
#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');
}
Please feel free to give any improvements/suggestions/contributions ;-)
Instead of printing to the Output window in VS as indicated by other answers, I prefer to create a console window in my GUI apps, then use regular printf or cout to write debugging info to it. This has the benefit that you can do it even when you run without the debugger.
See this site for a simple function that sets up a console.
I have used this in the past, although not with a win32 application. You could give it a shot though :)
http://www.cplusplus.com/forum/lounge/17371/
You can use the Windows function OutputDebugString (see here) to send output to debuggers. These outputs are shown in the VS output window. You can also watch these outputs with external applications, e.g. DebugView.
Remember to remove these statements from your production code if you don't want other people to see these debug messages (which would otherwise be possible using tools like DebugView...)

how to get function name and line number when project crashed in release mode

i have a project in C++/MFC
when i run its in debug mode and project crashed
i can get function and line number of code
with SetUnhandledExceptionFilter function
but in release mode i can not get it
i am test this function and source
_set_invalid_parameter_handler msdn.microsoft.com/en-us/library/a9yf33zb(v=vs.80).aspx
StackWalker http://www.codeproject.com/KB/threads/StackWalker.aspx
MiniDumpReader & crashrpt http://code.google.com/p/crashrpt/
StackTracer www.codeproject.com/KB/exception/StackTracer.aspx
any way to get function and line of code when project crashed in release mode
without require pdb file or map file or source file ?
PDB files are meant to provide you this information; the flaw is that don't you want a PDB file. I can understand not wanting to release the PDB to end users, but in that case why would you want them to see stack trace information? To me your goal is conflicting with itself.
The best solution for gathering debug info from end users is via a minidump, not by piecing together a stack trace on the client.
So, you have a few options:
Work with minidumps (ideal, and quite common)
Release the PDBs (which won't contain much more info than you're already trying to deduce)
Use inline trace information in your app such as __LINE__, __FILE__, and __FUNCTION__.
Just capture the crash address if you can't piece together a meaningful stack trace.
Hope this helps!
You can get verbose output from the linker that will show you where each function is placed in the executable. Then you can use the offset from the crash report to figure out which function was executing.
In release mode, this sort of debugging information isn't included in the binary. You can't use debugging information which simply isn't there.
If you need to debug release-mode code, start manually tracing execution by writing to a log file or stdout. You can include information about where your code appears using __FUNCTION__ and __LINE__, which the compiler will replace with the function/line they appear in/on. There are many other useful predefined macros which you can use to debug your code.
Here's a very basic TR macro, which you can sprinkle through out your code to follow the flow of execution.
void trace_function(const char* function, int line) {
std::cout << "In " << function << " on line " << line << std::endl;
}
#define TR trace_function(__FUNCTION__, __LINE__)
Use it by placing TR at the top of each function or anywhere you want to be sure the flow of execution is reaching:
void my_function() {
TR();
// your code here
}
The best solution though, is to do your debugging in debug mode.
You can separate the debug symbols so that your release version is clean, then bring them together with the core dump to diagnose the problem afterwards.
This works well for GNU/Linux, not sure what the Microsoft equivalent is. Someone mentioned PDB...?

Can I Access a calling function's name programmatically?

I'm hoping to add a little functionality to a Log File system for a project I'm working on. For my LogError() calls, I would like to include the function the error occurred in. I'm wondering if there's a way that I can access the name of the function that called LogError() so I can programmatically access that information to add it to the log.
For example:
bool Engine::GraphicsManager::Initialize(const HWND i_hWindow_main)
{
if ( !InitializeWindow( i_hWindow_main ) )
{
Engine::LogManager::Instance().LogError(L"GraphicsManager::Initialize - Unable to initialize graphics window");
return false;
}
Engine::LogManager::Instance().LogMessage(L"Graphics window initialized successfully");
/* SNIP */
initialized = true;
return true;
}
In the above example, I'd like LogError() to be able to determine that it was called from GraphicsManager::Initialize() and output (at least part of) that function's name instead of putting that in everywhere by hand.
EDIT: I should have mentioned that my LogError() function (and the other logging functions) are essentially wrappers for vfwprintf_s() so they can take variable length argument lists. While I like the "use a macro" suggestions, I'm not sure how to tackle that potential issue (which is likely another question).
Is this still reasonable/possible?
Thanks!
You could add an argument for the function name, and pass in the __FUNCTION__ macro: http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.80%29.aspx
And you could also define a macro that will automatically replace ...log...() with ...log...(__FUNCTION__).
These are predefined macros and part of the C/C++ standard which you can use:
__FILE__ __LINE__
They are explained here
Make a Logging macro
EDIT: Some fixes to deal with wide characters
//support macros
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define STRINGIZE(x) #x
#define __WFILE__ WIDEN(__FILE__)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define __WLINE__ WIDEN( STRINGIZE(__LINE__) )
// logging macro
#define LOG(msg) Engine::LogManager::Instance().LogError(__WFILE__ L"::" __WFUNCTION__ L":" __WLINE__ L" - " msg)
Use it like this
if( error ) { LOG(L"Error!"); }
logs
File.cpp::Function:Line - Error!
This works by using C-style string concatenation. "aa" "bb" -> "aabb" along with some operator pasting to put L before "astring". It uses the __FILE__, __FUNCTION__, and __LINE__ macros to report where the error was logged from. __LINE__ is translated into a string with the STRINGIZE macro. Due to crappy compliance with the standard, BOOST_PP_STRINGIZE is recommended if you plan on using boost anyway.