Home » Testing and Debugging » Debugging using C macros __FILE__ and __func__ and __LINE__

Debugging using C macros __FILE__ and __func__ and __LINE__

Following program shows a sample example of how we can use C macros __FILE__ , __func__ and __LINE__ to print the debug information which will show us, where is execution reached to, if any error it can print the line number of error and if in case of multi file programs like library, it can even show which file has some issues or we can also use it for verbose message during the development.

#include <stdio.h>
 
#define DEBUG_THIS printf("debug statement, in \n\tfile : %s, \n\tfunction: %s, \n\tLine : %d \n", __FILE__, __func__, __LINE__);
 
void debug_function (void) {
        printf("debug statement, in \n\tfile : %s, \n\tfunction: %s, \n\tLine : %d \n", __FILE__, __func__, __LINE__);
}
 
int main (int argc, char **argv) {
        printf("Main function, calling debug\n");
        debug_function();
        printf("back to Main\n");
        DEBUG_THIS;
        return 0;
}

In above program, we have written a function which when called prints the debug information or you can also use a macro DEBUG_THIS whenever you want to print the messages.

If you want to try and print date and time of execution of the program, you can use the program like below,

[#include <stdio.h>
#include <stdlib.h>
 
#define DEBUG 1
 
int main() {
#ifdef DEBUG
        printf("Compiled: " __DATE__ " at " __TIME__ "\n");
        printf("This is line %d of file %s\n", __LINE__, __FILE__);
#endif
        printf("hello world\n");
        exit(0);
}

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment