MFC TRACE Macro for Console Applications | CodeGuru

MFC TRACE Macro for Console Applications

The TRACE macro defined using MFC and ATL can also be used in console or Win32 application, however with some small modifications. This example will post Messages to the tracer built-in with Visual Studio IDE, TraceEx Also includes source file and code line which can be used as shortcut when double clicked on. /* Trace.h […]

Written By
CodeGuru Staff
CodeGuru Staff
Feb 21, 2001
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

The TRACE macro defined using MFC and ATL can also be used in console or Win32 application, however with some small modifications.

This example will post Messages to the tracer built-in with Visual Studio IDE, TraceEx Also includes source file and code line which can be used as shortcut when double clicked on.

/*
	Trace.h
*/

#ifndef __TRACE_H__
#define __TRACE_H__
#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 TraceEx _snprintf(szBuffer,TRACEMAXSTRING,”%s(%d): “,
                          &strrchr(__FILE__,’\’)[1],__LINE__);
_RPT0(_CRT_WARN,szBuffer);
Trace
#else
 inline void Trace(0);
 inline void TraceEx(0);
#endif
#endif // __TRACE_H__

Example

Here’s all you have to do to use this macro!

#include “trace.h”
int main(void)
{
 TraceEx(“Somethings wrongs here %dn”,1)
}

Running this application will result in the following output:

main.cpp(5): Somethings wrong here 1

Other features that could be included are ThreadID, ProcessID etc. fun debugging.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.