2008年4月21日 星期一

避免重複include標頭檔

假如有以下兩個header file: test.h和test2.h

// Header file test.h
const int LENGTH = 30;
.

// Header file test2.h
#include "test.h"
.
.

若有一程式片段如下:
// headerTest.cpp
#include "test.h"
#include "test2.h"
.
.

則會發生test.h被include兩次,造成LENGTH重複定義的問題。所以可以用以下方式來解決:
// Header file test.h
#ifndef H_test
#define H_test
const int LENGTH = 30;
#endif

0 意見: