在標頭檔裡寫下下面兩行相同的代碼:
typedef int X;
typedef int X;
gcc編譯馬上就會報redefinition of typedef 'X',換g++居然啥事沒有,怪異吧?於是去查文檔,發現C++裡是這樣描述的:“
In a given non-class scope, a
typedef
specifier can be used to redefine the name of any type declared in
that scope to refer to the type to which it already refers.
”嗯,看起來的確是C++針對non-class情況容忍了,像下面這種情況就報錯:
class A{
typedef int Y;
typedef int Y;
};
可惜在C語言標準裡找來找去,沒看到對redefinition的明確說明,不確定是不是其它C編譯器都會報錯。
我隨即想到了宏,於是嘗試了下面三種case:
Case1: #define M 1
#define M 1
Case2: #define M(x) x++
#define M(x) x++
Case3: #define M(x) (x+1)
#define M(x) (x + 1)
gcc/g++編譯(應該說這裡其實是前置處理器cc1/cc1plus)的結果是一致的,Case1/2都OK,Case3會報錯。查了下標準,是這樣描述的
(1) Tw o replacement lists are identical if and only if the preprocessing tokens in both have
the same number, ordering, spelling, and white-space separation, where all white-space
separations are considered identical.
(2) An identifier currently defined as an object-like macro shall not be redefined by another
#define preprocessing directive unless the second definition is an object-like macro
definition and the two replacement lists are identical. Likewise, an identifier currently
defined as a function-like macro shall not be redefined by another #define
preprocessing directive unless the second definition is a function-like macro definition
that has the same number and spelling of parameters, and the two replacement lists are
identical.
這裡的關鍵點就是,僅當兩者文字(完全一致,包括空白符)
http://hi.baidu.com/zhuxiaoyin/blog/item/f603f58e2e1321e2f11f3656.html