views:

226

answers:

6

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?

+5  A: 

Most compilers will show you the output after the prerocessing phases. For example, with gcc, you may use the -E flag.

Chris Young
+1  A: 

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.

John Leidegren
+2  A: 

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

Smashery
+1  A: 

if you need simply strip c sources from "#define" - you can use sed or awk

vitaly.v.ch
You'd also have to strip the #undef's too or else your compiler may bomb out about undeffing something that's not defined.
dreamlax
Well, its likely going to bomb out anyway, i.e. #define VERSION "1.0.2" ... (later, in main()) printf("%s\n", VERSION);
Tim Post
+1  A: 

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 :)

Tim Post
A: 

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.

Samir Talwar