cpreprocessor-directive

How to find __FUNCTION__, __LINE__ and __FILE__ of parent function?


I just made a fool of myself: I wanted to trace the execution of a process, and in order to do this, I had written a function trace(), which contains the following line of code:

printf("%s[%s:%d], %s\n", __FUNCTION__, __FILE__, __LINE__, s_message);

I hoped to see in which function I was, what file and what line within that file, but I just saw that information of the file where I programmed that trace() function.

Is it possible, is there some #define or so, to tell the C compiler to take the mentioned macros from the parent of the calling function?


Solution

  • You need to wrap it in a macro, e.g.:

    void _trace(char const *function, 
                char const *file, 
                long line, 
                char const *message) 
    {
        printf("%s[%s:%ld], %s\n", function, file, line, message);
    }
    
    #define trace(message) _trace(__FUNCTION__, __FILE__, __LINE__, (message))