SOGO論壇

標題: #if、#ifdef 等的使用 [列印本頁]

作者: mm117777    時間: 2012-7-20 09:59:56     標題: #if、#ifdef 等的使用

如果我們在一檔案欲 include 一檔頭檔 file1.h ,又想避免在同一檔案宣告兩次相同的東西,例如:


檔案 file1.h 含 extern int size
檔案 file2.h 含 #include "file1.h"
檔案 file3.h 含 #include "file1.h"

檔案 file.c 含 #include "file2.h" 及 #include "file3.h"
則在檔案 file.c 內,變數 size 重複宣告了兩次而產生錯誤。
欲避免這種情況發生,每個 #include "file1.h" 指令, 我們可以改變為如下指令:

      
      #if !define(FILE1)
      #define FILE1 "file1.h"
      #include FILE1
      #endif

或是
      #ifndef FILE1
      #define FILE1 "file1.h"
      #include FILE1
      #endif

註:

如果一個辨識名稱 X 沒有被 define 過, 則 define(X) 之值為 0, 或者 ifndef X 為真值。
當 file2.h 與 file3.h 都含上述指令, 如此一來 file1.h 僅能一次被加入 file.c 而不致於產生衝突。





歡迎光臨 SOGO論壇 (https://oursogo.com/) Powered by OURSOGO.COM