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.

Related :   C program to concatenate two strings using strcat

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);
}

lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded