Chapter 23

Global Variables and Macros


When you're writing programs, there are many types of data and operations that you must use again and again. Sometimes you have to do something as simple as creating a portable integer data type. Other times you need to do something a little more complex, like extracting a word from a long word value or storing the position of the mouse pointer. As you might know, Windows itself defines many constants and variables that you can use in your programs to help write programs faster. Using these previously defined constants and macros make your programs more portable and more readable by other programmers. Besides the macros, global constants, and variables defined by Windows, MFC adds its own set. In the following tables, you'll get a look at the most important of these globally available constants, macros, and variables.

Ten Categories of Macros and Globals

Because there are so many constants, macros, and globals, Visual C++ organizes its constants, macros, and globals into ten categories. Those categories are listed as follows. The following sections describe each of these categories and the symbols they define.

Application Information and Management Functions

Because a typical Visual C++ application contains only one application object but many other objects created from other MFC classes, you frequently need to get information about the application in different places in a program. Visual C++ defines a set of global functions that return this information to any class in a program. These functions, which are listed in Table 23.1, can be called from anywhere within an MFC program. For example, you frequently need to get a pointer to an application's main window. The following function call accomplishes that task.

CWnd* pWnd = AfxGetMainWnd();

Table 23.1 Application Information and Management

Function Description
AfxBeginThread() Creates a new thread.
AfxEndThread() Terminates a thread.
AfxGetApp() Gets the application's CWinApp pointer.
AfxGetAppName() Gets the application's name.
AfxGetInstanceHandle() Gets the application's instance handle, which is the instance from which the default resources were loaded.
AfxGetMainWnd() Gets a pointer to the application's main window.
AfxGetResourceHandle() Gets the application's resource handle.
AfxGetThread() Gets a pointer to a CWinThread object.
AfxRegisterClass() Registers a window class in an MFC DLL.
AfxRegisterWndClass() Registers a Windows’ window class in an MFC application.
AfxSetResourceHandle() Sets the instance handle that determines where to load the application's default resources.
AfxSocketInit() Initializes Windows Sockets.

ClassWizard Comment Delimiters

MFC defines a number of delimiters that ClassWizard uses to keep track of what it's doing, as well as to locate specific areas of source code. Although you'll rarely, if ever, use these macros yourself, you will see them embedded in your AppWizard applications, so you might like to know exactly what they do. Table 23.2 fills you in.

Table 23.2 ClassWizard Delimiters

Delimiter Description
AFX_DATA Starts and ends member variable declarations in header files that are associated with dialog data exchange
AFX_DATA_INIT In a dialog class's constructor, starts and ends dialog data exchange variable initialization
AFX_DATA_MAP In a dialog class's DoDataExchange() function, starts and ends dialog data exchange function calls
AFX_DISP Starts and ends OLE Automation declarations in header files
AFX_DISP_MAP Starts and ends OLE Automation mapping in implementation files
AFX_EVENT Starts and ends OLE event declarations in header files
AFX_EVENT_MAP Starts and ends OLE events in implementation files
AFX_FIELD Starts and ends member variable declarations in header files that are associated with database record field exchange
AFX_FIELD_INIT In a record set class's constructor, starts and ends record field exchange member variable initialization
AFX_FIELD_MAP In a record set class's DoFieldExchange() function, starts and ends record field exchange function calls
AFX_MSG Starts and ends ClassWizard entries in header files for classes that use message maps
AFX_MSG_MAP Starts and ends message map entries.
AFX_VIRTUAL Starts and ends virtual function overrides in header files

Collection Class Helpers

Because certain types of data structures are so commonly used in programming, MFC defines collection classes that enable you to get these common data structures initialized quickly and manipulated easily. MFC includes collection classes for arrays, linked lists, and mapping tables. Each of these types of collections contain elements that represent the individual pieces of data that comprise the collection. In order to make it easier to access these elements, MFC defines a set of functions, shown in Table 23.3, that you can override for a particular data type.

Table 23.3 Collection Class Helper Functions

Function Description
CompareElements() Checks elements for equality
ConstructElements() Constructs a new element (works similarly to a class constructor)
DestructElements() Destroys elements (works similar to a class destructor)
DumpElements() Provides diagnostic output in text form.
HashKey() Calculates hashing keys
SerializeElements() Saves or loads elements to or from an archive

CString Formatting and Message Box Display

If you've done much Visual C++ programming, you know that MFC features a special string class, called CString, that makes string handling under C++ less cumbersome. CString objects are used extensively throughout MFC programs. Even when dealing with strings in a resource's string table, CString objects can come in handy, as the following global functions, which replace format characters in string tables, show (see Table 23.4). There's also a global function for displaying a message box.

Table 23.4 CString Formatting and Message Box Functions

Function Description
AfxFormatString1() Replaces the format characters (i.e. %1) in a string resource with a given string
AfxFormatString2() Replaces the format characters "%1" and "%2" in a string resource with the given strings
AfxMessageBox() Displays a message box

Data Types

The most commonly used constants are those that define a portable set of data types. You've seen tons of these constants, which are named with all uppercase letters, used in Windows programs. You'll recognize many of these from the Windows SDK. Others are included only as part of Visual C++. You use these constants exactly as you would any other data type. For example, to declare a Boolean variable, you'd write something like this:

BOOL flag;

Table 23.5 lists the most commonly used data types defined by Visual C++ for Windows 95 and NT.

Table 23.5 Commonly Used Data Types

Constant Data Type
BOOL Boolean value
BSTR 32-bit pointer to character data used with OLE
BYTE 8-bit unsigned integer
COLORREF 32-bit color value
DWORD 32-bit unsigned integer
LONG 32-bit signed integer
LPARAM 32-bit window-procedure parameter
LPCRECT 32-bit constant RECT structure pointer
LPCSTR 32-bit string-constant pointer
LPSTR 32-bit string pointer
LPVOID 32-bit void pointer
LRESULT 32-bit window-procedure return value
POSITION The position of an element in a collection
UINT 32-bit unsigned integer
WNDPROC 32-bit window-procedure pointer
WORD 16-bit unsigned integer
WPARAM 32-bit window-procedure parameter

Diagnostic Services

After you have your program written, you're far from done. Then comes the grueling task of testing, which means rolling up your sleeves, cranking up your debugger, and weeding out all the “gotchas” hiding in your code. Luckily, MFC provides many macros, functions, and global variables that you can use to incorporate diagnostic abilities into your projects. Using these tools, you can do everything from printing output to a debugging window to checking the integrity of memory blocks. Table 23.6 lists these valuable diagnostic macros, functions, and global variables.

Table 23.6 Diagnostic Macros, Functions, and Global Variable

Symbol Description
AfxCheckMemory() Verifies the integrity of allocated memory.
AfxDoForAllClasses() Calls a given iteration function for all classes that are derived from CObject and that incorporate run-time type checking.
AfxDoForAllObjects() Calls a given iteration function for all objects that were derived from CObject and that were allocated with the new operator.
afxDump A global CDumpContext object that enables a program to send information to the debugger window.
AfxDump() Dumps an object's state during a debugging session.
AfxEnableMemoryTracking() Toggles memory tracking.
AfxIsMemoryBlock() Checks that memory allocation was successful.
AfxIsValidAddress() Checks that a memory address range is valid for the program.
AfxIsValidString() Checks string pointer validity.
afxMemDF A global variable that controls memory-allocation diagnostics. Can be set to allocMemDF, DelayFreeMemDF, or checkAlwaysMemDF.
AfxSetAllocHook() Sets a user-defined hook function that is called whenever memory allocation is performed.
afxTraceEnabled A global variable that enables or disables TRACE output.
afxTraceFlags A global variable that enables the MFC reporting features.
ASSERT Prints a message and exits the program if the assert expression is false.
ASSERT_VALID Validates an object by calling the object's AssertValid() function.
DEBUG_NEW Used in place of the new operator in order to trace memory-leak problems.
TRACE Creates formatted strings for debugging output.
TRACE0 Same as TRACE but requires no arguments in the format string.
TRACE1 Same as TRACE but requires one argument in the format string.
TRACE2 Same as TRACE but requires two arguments in the format string.
TRACE3 Same as TRACE but requires three arguments in the format string.
VERIFY Like ASSERT, but VERIFY evaluates the assert expression in both the Debug and Release versions of MFC. If the assertion fails, a message is printed, and the program is halted only in the Debug version.

Exception Processing

One of the newest elements of the C++ language is exceptions, which give a program greater control over how errors are handled. MFC increases the value of exceptions by defining a set of macros and functions that you can use to better handle errors in your applications. These macros and functions are listed in Table 23.7.

Table 23.7 Exception Macros and Functions

Symbol Description
AfxAbort() Terminates an application upon a fatal error
AfxThrowArchiveException() Throws an archive exception
AfxThrowDAOException() Throws a CDaoException
AfxThrowDBException() Throws a CDBException
AfxThrowFileException() Throws a file exception
AfxThrowMemoryException() Throws a memory exception
AfxThrowNotSupportedException() Throws a not-supported exception
AfxThrowOleDispatchException() Throws an OLE automation exception
AfxThrowOleException() Throws an OLE exception
AfxThrowResourceException() Throws a resource-not-found exception
AfxThrowUserException() Throws an end user exception
AND_CATCH Begins code that will catch specified exceptions not caught in the preceding TRY block
AND_CATCH_ALL Begins code that will catch all exceptions not caught in the preceding TRY block
CATCH Begins code for catching an exception
CATCH_ALL Begins code for catching all exceptions
END_CATCH Ends CATCH or AND_CATCH code blocks
END_CATCH_ALL Ends CATCH_ALL code blocks
THROW Throws a given exception
THROW_LAST Throws the most recent exception to the next handler
TRY Starts code that'll accommodate exception handling

The exception macros listed in Table 23.7 are included in MFC only to provide compatibility with earlier versions of the language. New programs should not use the macros, but rather the new exception-specific keywords such as try and catch.

See “Understanding Exceptions,” (ch. 21)

Message Map Macros

Windows is an event-driven operating system, which means that every Windows application must handle a flood of messages that flow between an application and the system. MFC does away with the clunky switch statements that early Windows programmers had to construct in order to handle messages and replaces those statements with a message map, which is nothing more than a table that matches a message with its message handler. In order to simplify the declaration and definition of these tables, MFC defines a set of message map macros. Many of these macros, which are listed in Table 23.8, will already be familiar to experienced MFC programmers.

Table 23.8 Message Map Macros

Macro Description
BEGIN_MESSAGE_MAP Begins a message map definition
DECLARE_MESSAGE_MAP Starts a message map declaration
END_MESSAGE_MAP Ends a message map definition
ON_COMMAND Begins a command-message message map entry
ON_COMMAND_RANGE Begins a command-message message map entry that maps multiple messages to a single handler
ON_CONTROL Begins a control notification message map entry
ON_CONTROL_RANGE Begins a control notification message map entry that maps multiple control IDs to a single handler
ON_MESSAGE Begins a user-message message map entry
ON_REGISTERED_MESSAGE Begins a registered user-message message map entry
ON_UPDATE_COMMAND_UI Begins a command-update message map entry
ON_UPDATE_COMMAND_UI_RANGE Begins a command-update message map entry that maps multiple command-update messages to a single handler

Runtime Object Model Services

Frequently in your programs, you need access to information about classes at runtime. MFC supplies a macro for obtaining this type of information in a CRuntimeClass structure. In addition, the MFC application frameworks relies on a set of macros to declare and define runtime abilities (such as object serialization and dynamic object creation). If you've used AppWizard at all, you've seen these macros used in the generated source code files. If you're an advanced MFC programmer, you might have even used these macros yourself. Table 23.9 lists the run-time macros and their descriptions.

Table 23.9 Runtime Services Macros

Macro Description
DECLARE_DYNAMIC Used in a class declaration to enable runtime class information access.
DECLARE_DYNCREATE Used in a class declaration to allow the class (derived from CObject) to be created dynamically. Also, allows runtime class information access.
DECLARE_OLECREATE Used in a class declaration to allow object creation with OLE automation.
DECLARE_SERIAL Used in a class declaration to allow object serialization, as well as runtime class information access.
IMPLEMENT_DYNAMIC Used in a class implementation to enable runtime class information access.
IMPLEMENT_DYNCREATE Used in a class implementation to allow dynamic creation of the object and runtime information access.
IMPLEMENT_OLECREATE Used in a class implementation to enable object creation with OLE.
IMPLEMENT_SERIAL Used in a class implementation to allow object serialization and runtime class information access.
RUNTIME_CLASS Returns a CRuntimeClass structure for the given class.

As you can see, the macros in Table 23.9 deal with run-time information. In addition to the macros, Run-Time Type Information (RTTI) was added to C++ so that programmers could obtain information about objects at runtime. This capability is especially useful when you're dealing with polymorphic objects, because it enables your program to determine at runtime what exact type of object it's currently working with.

See “Using Run-Time Type Information,” (ch. 21)

Standard Command and Window IDs

There are myriad standard messages that can be generated by a user of a Windows application. For example, whenever the user selects a menu command from a standard menu like File or Edit, the program sends a message. Each of these standard commands is represented by an ID. In order to relieve the programmer of having to define the dozens of IDs that are often used in a Windows application, MFC defines these symbols in a file called AFXRES.H. Some of these IDs have obvious purposes (for example, ID_FILE_OPEN), but many others are used internally by MFC for everything from mapping standard Windows messages to their handlers to defining string table IDs to assigning IDs to toolbar and status bar styles. There are far too many of these identifiers to list here. However, if you're interested in seeing them, just load the AFXRES.H file from your Visual C++ installation folder.