I'm implementing some code generators, i would like to know if there's any way in C, if a variable has already been declared ?
I was trying to find something using the preprocessor but without any succe开发者_开发问答ss...
thanks.
C is strictly static, you can't "lookup" if a variable has already been declared. If you are creating a code generator, why not read lines of code and see what's been declared?
No, there isn't. Doing so is much of what compilers do.
A common way to create unique a variable name is to use a very unlikely variable name, if possible combined with the line number. Something like
// beware, brain-compile code ahead!
a_rather_unlikely_variable_name_by_sbi_ ## __LINE__
Not really, no. Not unless you count attempting to use it and seeing if your code compiles.
You could try to hack something with the preprocessor for specific variables, sort of like the standard #ifdef
at the top of every include file. That wouldn't be scope-aware though, as the preprocessor runs way before the compiler does.
C isn't a very dynamic language that way.
Is the variable itself generated by your generator or something the user enters? When you generate the variable youself you can emmit a preprocessor token along with the variable and later check if that token exist.
i'm pretty late, well there is an easy way to know this, with text files; write the variable name inside a file right when you declare it, and then check later if the name is written. just make 3 macros "DEF" "IF_DEF" and "IF_NOT_DEF" and it looks good. You can't look up in C, but you can look up inside a file. But it does take some memory.
精彩评论