C/C++的redefinition

來源:互聯網
上載者:User

在標頭檔裡寫下下面兩行相同的代碼:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.