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);
}
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply