Wednesday, December 24, 2008

[C/C++] #pragma message for compilation errors

You might have faced compilation errors in which you cannot actually find the source from where it is coming. I have faced such situations and in most of the cases same can be solved (or atleast get a clue) on knowing from which file or from which context the error is happening. And here is a preprocessor directive which will help you for finding the cause or source behind your compilation errors.

#pragma message( messagestring )

For example please see the below code with #pragma message and its compilation output(in to VC++ output window).

Code
// Test.cpp : Defines the class behaviors for the application.//
#pragma message ("------------Before include stdafx.h---------")
#include "stdafx.h"
#pragma message ("------------Before include Test.h---------")
#include "Test.h"
#pragma message ("------------Before include MainFrm.h---------")
#include "MainFrm.h"
#pragma message ("------------Before include IpFrame.h---------")
#include "IpFrame.h"
#pragma message ("------------Before include TestDoc.h---------")
#include "TestDoc.h"
#pragma message ("------------Before include TestView.h---------")
#include "TestView.h"
#pragma message ("------------Before include TestView.h---------")

Output window
--------------------Configuration: Test - Win32 Debug--------------------
Compiling...Test.cpp
------------Before include Test.h---------
------------Before include MainFrm.h---------
------------Before include IpFrame.h---------
------------Before include TestDoc.h---------
------------Before include TestView.h---------
------------Before include TestView.h---------

You can use the #pragma else where in your program and your mesage will be displayed in the debug output window. The messagestring parameter of #pragma message () can be a macro that expands to a string literal, and you can concatenate such macros with string literals in any combination. If you use a predefined macro in the message pragma, the macro should return a string, else you will have to convert the output of the macro to a string.

No comments: