Reputation: 1525
Here is my code:
macro1.h
#ifndef NO_DEBUG
#define DEBUG(arg) cout<<endl<<arg<<endl
#else
#define DEBUG(arg)
#endif
macro1.cpp
#include <iostream>
#include "macro1.h"
using namespace std;
int main()
{
cout<<endl<<"start"<<endl;
DEBUG("debug line 1");
#undef NO_DEBUG
DEBUG("debug line 2");
#define NO_DEBUG
DEBUG("debug line 3");
cout<<endl<<"end"<<endl;
return 0;
}
I compile/run it like this:
Compile + Run 1:
$ g++ macro1.cpp
$ ./a.out
start
debug line 1
debug line 2
debug line 3
end
$
Compile + Run 2:
$ g++ macro1.cpp -DNO_DEBUG
$ ./a.out
start
end
$
But that is not what I expected, In the first run since NO_DEBUG is not defined it had to print:
start
debug line 1
debug line 2
end
In second run, we are defining macro through command line so it had to print:
start
debug line 2
end
So can some one please tell me what is going on here?
I am using only pre-processing features so It should work right?.
Upvotes: 1
Views: 139
Reputation: 950
It looks like you are misunderstanding how the preprocessor works. Here is a good, quick tutorial: http://www.cplusplus.com/doc/tutorial/preprocessor/
As for your particular problem: the DEBUG macro is only defined once based on the NO_DEBUG macro definition. Once the preprocessor decides which definition to use, you can no longer change the definition of the DEBUG macro. You are trying to use the #unset/#defines to accomplish this but as @Baum mit Augen pointed out, the preprocessor is just a text replacement engine and very "dumb". It doesn't do anything fancy other than replace text.
So by the time you get to your actual DEBUG macros being used, they only have one definition based on NO_DEBUG and you will either get everything printing or nothing printing, as you saw.
Upvotes: 1