How can I write a program in C which removes all the defined values defined by the user using #define name value?
Throughout the program should we replace the name, value?
Does anyone have any examples of this?
How can I write a program in C which removes all the defined values defined by the user using #define name value?
Throughout the program should we replace the name, value?
Does anyone have any examples of this?
Most compilers will show you the output after the prerocessing phases. For example, with gcc, you may use the -E flag.
That can't be done. You have to know the name of the macro you wish to undefine. You can extract all these through some clever parsing but you can not simply say undef ALL unless there's some way to tell your compiler to do exactly that. I would recommend you look up any compiler specific documentation you can.
To remove #defined values individually, you can use #undef:
#define A_CONSTANT 3.14
#undef A_CONSTANT
// A_CONSTANT is no longer defined
I don't think there's a way to remove all #defined names, unless it's compiler-specific
if you need simply strip c sources from "#define" - you can use sed or awk
It looks like you need to implement your own primitive preprocessor, but nobody has showed you how lexical parsers work, or you would not be asking :)
With all of the syntatic goop that goes into parsing C, surely, preprocessor tokens are the easiest to extract.
I don't think someone could cram 'parsers for the parser challenged' into a single SO answer .. but a few of these crazy folks may try :)
If your goal is to remove all the #define
directives from the code, as opposed to undefining them later or something, this can be done with a simple regular expression find-and-replace. As this is homework, I imagine I shouldn't be showing you exactly how to do it, but if I tell you that /\nsometext[^\n]*/
should find any lines starting with "sometext". This may be slightly different depending on which specific brand of regex syntax you choose to use, but this'll work in most text editors with regular expression support that I've used, and I think it'll work with sed
too if you provide the -E
switch - it turns on extended regexes.
From there, you should be able to figure out the rest.