Home > OS >  Are functions external by default?
Are functions external by default?

Time:02-20

Is a function without a storage class specified in its declaration and definition :

void func(void); // declaration

void func(void) { // implementation
    
}

be equivalent to the function with extern storage class in its declaration and definition? :

extern void func(void); // declaration

extern void func(void) { // implementation
    
}

CodePudding user response:

From the C Standard (6.2.2 Linkages of identifiers)

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.

CodePudding user response:

Identifiers for functions always have external linkage by default. Storage class is a separate issue.

Some rules about declarations are:

  • For declarations outside of functions, all identifiers have external linkage by default.

  • For declarations inside of functions, identifiers for functions have external linkage by default, and identifiers for objects have no linkage by default.

  • If the declaration includes static, the identifier has internal linkage.

By these rules, identifiers for functions have external linkage by default, have internal linkage if declared with static, and never have no linkage. There are additional rules for declarations which are not fully described here. The rules are a mishmash and a bit complicated due to the history of how C developed. Different C implementations did things in different ways, and the C standardization committee had to tie things together.

Functions do not have storage classes. Storage classes, or more properly, storage durations, are categories for the lifetimes of objects. extern and static are keywords called storage-class specifiers, which are different from storage classes (the same way “fox” and “dog” are words for animals but are not animals). Storage-class specifiers partly affect storage classes of objects, but they also affect linkages of identifiers and other things. Linkage of function identifiers is the issue here, not storage class. Linkage is the process by which declarations of identical identifiers in different places can be made to refer to the same object or function. Because of the complications in C history, the extern keyword causes external linkage for identifiers in a new declaration, and static causes internal linkage. (In a redeclaration of a visible identifier, extern does not change the prior linkage; in static int x; extern int x;, x still has internal linkage in the latter. As stated, the rules are complicated.)

  • Related