Reputation: 492
test.cpp
#include <iostream>
#include "Class1.h"
#define DEBUG
int main() {
checkAssert();
}
Class1.h
#include <cassert>
#ifndef CLASS1_H_
#define CLASS1_H_
#if defined(DEBUG)
void checkAssert(){
int number = 10;
assert(number == 10);
}
#else
void checkAssert(){
std::cout << "opps" << std::endl;
}
#endif /* DEBUG */
#endif /* CLASS1_H_ */
1. I have defined DEBUG in main file.
2.In Class1.h #if defined(DEBUG) is for check if DEBUG is defined or not(according to my understanding).
I am trying this program to understand how DEBUG macro works in c++, But every time I have opps output in the screen. Can anyone please help me to understand what is going on.
Upvotes: 1
Views: 58
Reputation: 16421
Preprocessor does text substitution. Once it pastes class1.h
into your TU's file you have (I ignored expanding standard headers for the sake of brevity)
#include <iostream>
#include <cassert>
#ifndef CLASS1_H_
#define CLASS1_H_
#if defined(DEBUG)
void checkAssert(){
int number = 10;
assert(number == 10);
}
#else
void checkAssert(){
std::cout << "opps" << std::endl;
}
#endif /* DEBUG */
#endif /* CLASS1_H_ */
#define DEBUG
int main() {
checkAssert();
}
As you can see, DEBUG
is defined after the check for it. Simply move it above the relevant #include
to get the behaviour you want.
Upvotes: 1
Reputation: 118292
Your test.cpp
sets the macro after the header file is included already. That's too late. You have to set the macro before including the header file:
#define DEBUG
#include <Class1.h>
Upvotes: 4