Programmatic way to get variable name in C?

前端 未结 10 1798
广开言路
广开言路 2020-11-29 23:08

I am developing a tool to dump data from variables. I need to dump the variable name, and also the values.

My solution: Store variable name as a string, and print th

相关标签:
10条回答
  • 2020-11-29 23:49

    Shorter way:

    #define GET_VARIABLE_NAME(Variable) (#Variable)
    

    test:

    #include <string>
    class MyClass {};
    
    
    int main(int argc, char* argv[]) {
        int foo = 0;
    
        std::string var_name1 = GET_VARIABLE_NAME(foo);
         char* var_name2 = GET_VARIABLE_NAME(foo);
         char* var_name3 = GET_VARIABLE_NAME(MyClass);
    
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 23:50

    If your executable is compiled with debugging information, you may be able to get this info. If not, you're probably out of luck. So you're building a debugger? Why? Existing debuggers for c are very mature. Why not use existing tools instead of re-inventing the wheel?

    0 讨论(0)
  • 2020-11-29 23:52

    Despite the very precise answer from @Matt Joiner, I wanna write a full short code exemplifying this just to see how simple it is using #define macro

    #include <stdio.h>
    #define dump(v)printf("%s",#v);
    int main()
        {
        char a;
        dump(a);
        }
    

    output: a

    0 讨论(0)
  • 2020-11-29 23:54

    You could try something like this:

    #define DUMP(varname) fprintf(stderr, "%s = %x", #varname, varname);
    

    I used to use this header I wrote, when I was new to C, it might contain some useful ideas. For example this would allow you to print a C value and provide the format specifier in one (as well as some additional information):

    #define TRACE(fmt, var) \
            (error_at_line(0, 0, __FILE__, __LINE__, "%s : " fmt, #var, var))
    

    If you're using C++, you could use the type of the passed value and output it appropriately. I can provide a much more lucrative example for how to "pretty print" variable values if this is the case.

    0 讨论(0)
提交回复
热议问题