Treating __func__ as a string literal instead of a predefined identifier

前端 未结 4 1815
佛祖请我去吃肉
佛祖请我去吃肉 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:40

    Remark that, "__func__ is not a function so it cannot be called; in fact, it is a predefined identifier that points to a string that is the name of the function, and is only valid inside the scope of a function." - Jonathan.

    The following is what you are looking for:

    #define TO_STR_A( A ) #A
    #define TO_STR( A ) TO_STR_A( A )
    #define INFO_MSG TO_STR( __LINE__ ) ":" __FILE__
    
    char buff[ 256 ] = { 0 };
    
    sprintf( buff, "Something bad happened here, %s in function %s().", INFO_MSG, __func__ );
    printf( "INFO: %s\n", buff );
    

    ... note that a call to __func__ can be made inside the function itself. See this.

提交回复
热议问题