Linkage Types

    技术2022-05-11  69

    Objects, references, functions, types, templates, and namespaces are all considered names. A name can have one of three linkage types: external linkage, internal linkage, or no linkage. The linkage type of a name specifies its visibility from other scopes and translation units. A name with external linkage can be referred to from every translation unit of the program. Examples of such names include ordinary functions that aren't explicitly declared as static, global objects, const objects explicitly declared extern, classes, enumerations and their enumerators, templates, namespaces, and so on. Here are a few examples of names with external linkage:

     

    int  n;  // global non-static, hence external linkage class  C{  void  f();  //  member functions   static   int  n; //  static data members }; extern   const  K;  // defined in a different translation unit void  func (); namespace  NS{  class  D{};  //  qualified name NS::D has external linkage } enum  DIR{ Up, Down}  //  DIR, Up, and Down have external linkage

    A name with internal linkage is visible only from within the translation unit in which it was declared. A name declared in a namespace scope (that is, declared globally or within a namespace) has internal linkage if it's the name of a static object, a static function, a member of an anonymous union, a member of an anonymous namespace, a typedef name, or a const object not declared extern. Here are some examples of names with internal linkage:

     

    static   void  f();  // a static function static   int  q;  // a static object declared in global scope namespace   // members of anonymous namespace class  C{};  int  x; } const  M = 1000 // const object not declared extern union{  // members of an anonymous union   int  x;  float  y;};typedef  int  I;  //  typedef names

    Names with no linkage are visible only in the scope in which they're declared. Such names include local objects, local classes, and other local types. Put differently, any name that has neither external linkage nor internal linkage has no linkage. Here are some examples of such names:

    int  main(){  class  C{};  //  C is a local class; has no linkage   int  j;  //  local object not declared extern has no linkage  C c;  //  the object c has no linkage   enum  Parity  //  local enum and enumerators  { Even, Odd };}

     

     原文章地址: http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=41&rl=1

    最新回复(0)