星期五, 2月 12, 2010

[轉]#ifdef _DEBUG

以前看過,不過這種東西一陣子沒看又忘掉了,所以還是把他存起來。

連結http://huenlil.pixnet.net/blog/post/24339151

接下來則是在知識+看到的,一些小問題知識家還是有不錯的答案可以參考。
連結

#ifndef _STDLIB_H_
#define _STDLIB_H_
... some code
....

#endif // of _STDLIB_H_

這樣的用法一般會寫在header file 當中.
目的是為了避免重覆include 同一個header file compiler 會發出重覆宣告的錯誤

用法如下
#ifndef _STDLIB_H_ // 如果沒有定義_STDLIB_H_ 這個macro 則下面的code 會被展開直到 #endif
#define _STDLIB_H_ // 定義 _STDLIB_H_


#endif // 結束 前制處理器的if 判斷 區段


所以當user 第一次include 時. _STDLIB_H_ 還沒被定義過. 此時#ifndef 到 #endif 的code 會被展開. 又此段當中有一個#define _STDLIB_H_ . compiler 就會記住_STDLIB_H_ 被定義過
當第二次在include 同一個檔案. compiler 發現 _STDLIB_H_ 被定意過了. 此時#ifndef 到 #endif 之間的code 就不會被展開了.
達到防止重覆include 的效果


example program 共3 個檔案
-----------------------------------------
file : abc.h
#ifndef _ABC_H_
#define _ABC_H_

const int a=100;

#endif // of _ABC_H_

-----------------------------
file : 123.h
#include "abc.h"


-----------------------------
file : main.cpp
#include "123.h"
#include "abc.h"

int main()
{
return 0;
}

把上面三個檔分別存成abc.h 123.h 跟main.cpp
compiler main.cpp 妳會發現不會有錯誤發生.
但是如果把abc.h 去除#ifndef _ABC_H_ 等等 如下面
file : abc.h
// 沒有#ifndef _ABC_H_ 的abc.h

// #ifndef _ABC_H_ <== mark 掉
// #define _ABC_H_ <== mark 掉

const int a=100;

// #endif <== mark 掉

再次compiler main.cpp
妳會發現compiler 會跟妳說 a 重覆宣告
VC 的error 如下
f:\temp\abc.h(7) : error C2370: 'a' : redefinition; different storage class
f:\temp\abc.h(7) : see declaration of 'a'