Thursday, June 17, 2010

Extra-ordinary Debugging Provisions from GCC Compiler

In Linux, one of the best and efficient debugging tools is printf statement.I think many of us know this. But i learnt the best usage of this printf statement recently. I am sharing the same with you.

When i was reading some Linux device driver code, written by one of my colleagues, i saw some different printf statements which i never seen before.

Those were like

    printf(">> %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

When i saw this code, i was trying to find out where these were declared and some information on these inside the code. After some time, discussion with my lead made me to know about this.

These are very good 'tools' provided in GCC compiler. In many cases, when we are working in Linuc/Unix environment, printf is a simple and efficient debugging tool.

Normally we use like, at the beginning of each function,

    printf(">> %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

and the at the end of each function as,

    printf("<< %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);

Please look into the first characters of these printf statemtnes carefully. These statements are started with '>>' and '<<' symbols which designates the entering to the functions and leaving from the functions. These informations clearly says that, while debugging, which functions called when and when the control has come out. This information will be very very useful to find out the cause or reason for the error. At the first run itself, by looking into the output, we can suspect where the 'nonsense' is happening.

Here __FILE__ gives the filename. __LINE__ gives the line number and __FUNCTION__ gives the name of the function. These are all macros defined by default and no need to do any manual stuffs.


At the beginning of my job, i was using the printf statements only for debgging in linux. But i was not using these macros, even i didnt know about these at all....! I was using like, one printf for one run! Say, i have one main.c and other 3 C files in my project. Each 3 files having one function defined in that. If any error is coming in 3rd C file, i should go from main.c to 3rd C file to confirm that in 3rd C fille only error is occuring. To achive this, 3 printf statements and 3 runs are required. Simply waste of time. If i use above methodology, i can come to know at the first RUN itself.

I was really felt well when i came to know about these thing. Now am not writing any function without these 'mechanisms'.....

I am sure you all will definitely feel the same...

Gud LucK....

(Please drop a mail to pramoda.ma@gmail.com if u find any mistakes here)