2016-10-02 46 views
1

TEST.CPP混淆DEBUG宏

#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.我在主文件中定義DEBUG。

2.In Class1.h #if defined(DEBUG)用於檢查DEBUG是否被定義(根據我的理解)。

我試圖通過這個程序來了解DEBUG宏如何在C++中工作,但每次我在屏幕上都有opps輸出。 任何人都可以請幫我理解發生了什麼事。已列入

回答

4

test.cpp套宏頭文件。太遲了。你必須設置宏包括頭文件:

#define DEBUG 
#include <Class1.h> 
+0

它完美的作品。非常感謝你.. :) –

+0

@RashedAzad,如果這回答你的問題(我相信它),那麼你應該標記這個答案是正確的。 – Mikkel

1

預處理程序所做的文本替換。一旦粘貼class1.h到您的TU文件,你有(我忽略了擴大標準的頭爲簡潔起見)

#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(); 
} 

正如你所看到的,DEBUG是在檢查之後確定。只需將其移動到相關的#include之上即可獲得您想要的行爲。