2013-10-05 23 views
1

我知道大約從C標準以下摘錄介紹Ç鏈接規則:爲什麼stdlib.h中充滿外部函數原型和gcc差異這個

1/ An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. There are three kinds of linkage: external, internal, and none.

2/ In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

3/ If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

4/ For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5/ If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

6/ The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.

7/ If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

我明白extern關鍵字是功能之前,可選聲明,因爲它們是在默認情況下的外部,但也有通過的extern stdlib.h中之前的一些功能原型,如:

extern void qsort (void *__base, size_t __nmemb, size_t __size, 
      __compar_fn_t __compar) __nonnull ((1, 4)); 

另外,爲什麼GCC負責處理點7所描述的情況不同,當涉及到函數和變量。在此示例中這兩個函數foo和變量d是在內部和外部的範圍限定兩者但僅變量定義引發錯誤:

static int foo(void); 
int foo(void); /* legal */ 

static double d; 
double d; /* illegal */ 

回答

0

一個可以自由地放置或之前函數聲明不到位的extern,因此它不應該是令人驚奇的是人們可以在某處找到它。關於第二個問題:

C11草案(n1570.pdf)在與暫定定義159頁有例如:

static int i5; // tentative definition, internal linkage 
// ... 
int i5; // 6.2.2 renders undefined, linkage disagreement 
extern int i5; // refers to previous, internal linkage 

6.2.2爲您發佈的內容。所以,在這種情況下它不起作用,因爲有兩個不同聯繫的試探性定義,所以存在p.7違規。另一方面,它與外部說明符一起工作(因爲你的例子中有foo函數),因爲p.4是強制的 - 稍後的聲明指的是在第一個聲明中定義的鏈接。換句話說,變量的情況下不起作用,因爲它們是對象並涉及暫定義的定義規則。至少標準包含明確的例子,清楚地解釋了合作者想說的內容。

相關問題