jump to navigation

c-faq review and a chinese translation (1.9) February 1, 2007

Posted by TSAI HONG-BIN in Programming.
trackback

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

1.9 How can I make a sort of “semi-global” variable, that is, one that’s private to a few functions spread across a few source files?

You can’t do this in C. If it’s impossible or inconvenient to put all the functions in the same source file, there are two usual solutions:

  1. Pick a unique prefix for the names of all functions and global variables in a library or package of related routines, and warn users of the package not to define or use any symbols with names matching that prefix other than those documented as being for public consumption. (In other words, an undocumented but otherwise global symbol with a name matching that prefix is, by convention, “private.”)
  2. Use a name beginning with an underscore, since such names shouldn’t be used by ordinary code. (See question 1.29 for more information, and for a description of the “no man’s land” between the user and implementation namespaces.)

It may also be possible to use special linker invocations to adjust the visibility of names, but any such techniques are outside of the scope of the C language.

1.9 我如何可以製造一個「半全域」的變數,也就是說,一個對少數函式而言屬於隱域,卻可以在程式碼之間傳遞的變數?

你無法在c語言裡這麼做。同時,也不可能將所有的函式放在同一個源碼檔裡頭,也不會比較方便。不過有兩個常用的解法:

1. 替你所包裝的函式庫裡的函式或變數取一個特別的前綴(prefix),並警告使用者不要定義或使用和該前綴相同的名字,已標明為public的除外。(也就是說,沒有標明public的全域變數,且名字和前綴相符者就是private)

2. 名字前加上下畫線(underscore) (按: __VAR),但這種命名不應使用在一般的程式碼裡。(請參考問題1.29)

也可以使用特別的連結器來調整變數名稱的可見度,但這種功能是屬於C語言的範疇之外的。

Advertisements

Comments»

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: