Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if __PRETTY_FUNCTION__ can be used?

...../PluginLoader.h:34: multiple definition of 'Dummy_Func_For_Generating_FUNCTION_NAME_Macro()'

The above error is output for the below code. I have include guards in my file. And everything else compiles fine.

EDIT: What I was trying to achieve was to check if __PRETTY_FUNCTION__ was defined, and if it was, use it later in code via FUNCTION_NAME macro (For logging purposes). If __PRETTY_FUNCTION__ is not defined, use next best thing and so on. However, the responses I got made me realize that this impossible. So, if __PRETTY_FUNCTION__ and all these others are not macros, what are they? And how do I check if a certain implementation has one of them or not?

    void Dummy_Func_For_Generating_FUNCTION_NAME_Macro()
    {
#ifndef FUNCTION_NAME
    #ifdef __PRETTY_FUNCTION__
        #define FUNCTION_NAME __PRETTY_FUNCTION__
    #elif __FUNCTION__
        #define FUNCTION_NAME __FUNCTION__
    #elif __func__
        #define FUNCTION_NAME __func__
    #else
        #define FUNCTION_NAME ""
    #endif
#endif
    }
like image 497
nakiya Avatar asked Nov 12 '10 11:11

nakiya


2 Answers

void Dummy_Func_For_Generating_FUNCTION_NAME_Macro() is a function, not a macro. Functions don't create macros. Macros are resolved in preprocessor phase, and functions in compiler phase. Remove the function definition, and leave only #ifndef block.

Use compiler identifying macros to figure out which function identifying macro to use. For instance:

#ifdef _MSC_VER // Visual Studio
    #define FUNCTION_NAME __FUNCTION__
#endif
like image 132
Dialecticus Avatar answered Sep 22 '22 11:09

Dialecticus


__PRETTY_FUNCTION__ and __FUNCTION__ are not preprocessor macros like __LINE__ or __FILE__, but magic constants they are not available at preprocessor time, but later at compile time (in function scope).

So whatever you are trying to do with macros here will probably not work anyway.

However the compiling error is probably a problem with guard. I succeed compiling a not very different program (see below) without any problem. But as I said above, FUNCTION_NAME will always be set to empty string.

xx.h header file

#ifndef H_XX_H
#define H_XX_H

#ifndef FUNCTION_NAME
    void Dummy_Func_For_Generating_FUNCTION_NAME_Macro()
    {
    #ifdef __PRETTY_FUNCTION__
        #define FUNCTION_NAME __PRETTY_FUNCTION__
    #elif __FUNCTION__
        #define FUNCTION_NAME __FUNCTION__
    #elif __func__
        #define FUNCTION_NAME __func__
    #else
        #define FUNCTION_NAME ""
    #endif
   ;
   }
#endif
#endif

xx.c source file

#include <stdio.h>
#include "xx.h"

main(){
    printf("%s\n", FUNCTION_NAME);
}
like image 28
kriss Avatar answered Sep 19 '22 11:09

kriss