Do classes have external linkage?

后端 未结 5 2094
梦谈多话
梦谈多话 2020-12-16 01:00

I have 2 files A.cpp and B.cpp which look something like

A.cpp
----------
class w
{
public:
    w();
};


B.cpp
-----------
class w
{
public:
    w();
};
         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 01:38

    The class declaration

    class w
    {
    public:
        w();
    };
    

    does not produce any code or symbols, so there is nothing that could be linked and have "linkage". However, when your constructor w() is defined ...

    w::w()
    {
      // object initialization goes here
    }
    

    it will have external linkage. If you define it in both A.cpp and B.cpp, there will be a name collision; what happens then depends on your linker. MSVC linkers e.g. will terminate with an error LNK2005 "function already defined" and/or LNK1169 "one or more multiply defined symbols found". The GNU g++ linker will behave similar. (For duplicate template methods, they will instead eliminate all but one instance; GCC docs call this the "Borland model").

    There are four ways to resolve this problem:

    1. If both classes are identical, put the definitions only into one .cpp file.
    2. If you need two different, externally linked implementations of class w, put them into different namespaces.
    3. Avoid external linkage by putting the definitions into an anonymous namespace.
    namespace
    {
      w::w()
      {
        // object initialization goes here
      }
    }
    

    Everying in an anonymous namespace has internal linkage, so you may also use it as a replacement for static declarations (which are not possible for class methods).

    1. Avoid creating symbols by defining the methods inline:
    inline w::w()
    {
      // object initialization goes here
    }
    

    No 4 will only work if your class has no static fields (class variables), and it will duplicate the code of the inline methods for each function call.

提交回复
热议问题