C/C++的redefinition

  • Post author:
  • Post category:其他

在头文件里写下下面两行相同的代码:

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