tags:

views:

83

answers:

4

hi,

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 success...

thanks.

+5  A: 

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?

Abbas
actually i'm generating several versions of the file and then i'm generating a whole bunch of patches. These patches insert macros, and some macros expand to declarations, so i cannot know everything at generation time, because the patch combination can be quite tricky
LB
A: 

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.

T.E.D.
i agree, but i cannot find a CPP trick...
LB
+1  A: 

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__
sbi
A: 

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.

Rudi