Treating __func__ as a string literal instead of a predefined identifier

前端 未结 4 1811
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 14:07

I am using gcc to compile C99 code. I want to write a macro which will return a string containing the function name and line number.

This is what I have:

<         


        
4条回答
  •  遥遥无期
    2020-12-16 14:29

    After a quick experiment I found that you cannot use __func__ with stringification. It would not make much sense if you could as this would mean that the value would be wherever the macro is defined instead of where it is applied.

    The nature of __func__, as noted in the comments on the question, is described in this answer.

    Stringification is performed at pre-processor time and because of that __func__ is unavailable as it is essentially a function local string that is defined later on the compilation process.

    However you can use __func__ in a macro as long as you don't use stringification on it. I think the following performs what you're after:

    #include 
    
    #define INFO_MSG "Something bad happened here: %s : %s(), at line: %d", \
                     __FILE__, __func__, __LINE__
    
    int main()
    {
        char buff[256] = {'\0'};
        sprintf(buff, INFO_MSG);
        printf("INFO: %s\n", buff);
        return 0;
    }
    

    Note that there's no particular reason, in the question as presented, to use a string buffer. The following main function would achieve the same effect without the possibility of buffer overrun:

    int main()
    {
        printf("INFO: ");
        printf(INFO_MSG);
        printf("\n");
        return 0;
    }
    

    Personally, I'd wrap up the whole process in the macro like this:

    #include 
    
    #define INFO_MSG(msg) printf("%s: %s : %s(), at line: %d\n", \
                            msg, __FILE__, __func__, __LINE__)
    
    int main()
    {
        INFO_MSG("Something bad happened");
        return 0;
    }
    

提交回复
热议问题