jump to navigation

c-faq review and a chinese translation (1.10) February 2, 2007

Posted by TSAI HONG-BIN in Programming.

plz refer to http://c-faq.com/decl/static.html

1.10 Do all declarations for the same static function or variable have to include the storage class static?

The language in the Standard does not quite require this (what’s most important is that the first declaration contain static), but the rules are rather intricate, and are slightly different for functions than for data objects. (There has also been a lot of historical variation in this area.) Therefore, it’s safest if static appears consistently in the definition and all declarations.Additional links: An article by Jutta Degener explaining the subtly different rules for static variables versus static functions.References: ISO Sec.
Rationale Sec.
H&S Sec. 4.3 p. 75

所有static 的函式或變數都必須在宣告時加上儲存類別 static 嗎?(按:storage class: auto, register (變數存在 register 而非 ram), static (compile time即完成初始化,只能在本地域使用), extern (變數在其他源碼裡定義), typedef)

標準的語言規範裡並沒有要求,但最重要的是第一個宣告必須含static,但實際運作上的規則有點複雜,而且對於函式和資料物件(按:指變數)的處理有所不同。(還包括一些歷史上的變化) 因此,最安全的方法就是一致地讓 static 同時出現在宣告及定義的部份。

補充 Jutta Degener 解釋static變數和static函式的不同:


/* object */ /* function */

case 1 –>

int o1; int f1(); /* external linkage */
static int o1; static int f1(); /* ERROR, both have external linkage */

case 2 –>

static int o2; static int f2(); /* internal linkage */
int o2; /* ERROR, o2 has internal linkage */
int f2(); /* OK, picks up internal linkage */

case 3 –>

static int o3; static int f3(); /* internal linkage */
extern int o3; extern int f3(); /* OK, both pick up internal linkage */

The difference is case (2); where functions do pick up a previous linkage even without “extern”, objects don’t.



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: