Friday, June 08, 2007

__FILE__, __LINE__ and __cplusplus macro

we often meet the __FILE__ macro in an MFC application. it seems MFC macro.But it is one of the c++ predefined macro. __FILE__ macro is available in C++ . __LINE__ macro is also available in C++.


__FILE__ & __LINE__ macros specified in C & C++ standards are useful to provide some debugging information, during run-time. During pre-processing stage of compilation,

__FILE__ macro expands to the name of the file being compiled, in the form of a C string constant;
__LINE__ expands to the line number of the source file that is being compiled, in the form of an integer constant.




Simple Example with them :
-----------------------------------

Filename is "C:\MacroTesting.cpp"
-------------------------------------------

#include
#include

int main(int argc, char **argv)
{
FILE *fd;

char errinfo[100];

fd = fopen ("C:\Test.txt" , "r");
if (fd == NULL)
{
sprintf (errinfo, "Error at line %d of %s", (__LINE__ - 3), __FILE__);
perror (errinfo);
free (errinfo);
}
else
{
printf ("file descriptor = %d", fileno(fd));
fclose (fd);
}

return (0);
}



In the above program we are opening "C:\test.txt" in read mode.

if the file is not available, then it will displays error as follows :

Output :

Error at line 14 of C:\MacroTesting.cpp

This will be very useful for identifying errors in an application ( if the application has so many files at that time it will be very

useful to identify where the program failed...)





__cpluscplus macro C++
----------------------------------


#ifdef __cplusplus
extern "C" {
#endif

DECLARE_INTERFACE_(IHistogram, IUnknown)
{

STDMETHOD(GetParams) (THIS_ HistogramParams *irp ) PURE;

};

#ifdef __cplusplus
}
#endif

No comments: