C++使用 header 定义的模板类乘以定义的符号

标签 c++ templates visual-studio-2005

我正在 visual studio 2005 中开发一个包含 DLL 和 EXE 的项目。DLL 的代码中有一个可增长数组类的模板:

template <class Type>
class GArray
{
    Type *p;
    uint32 len;
    uint32 alloc;

protected:
    bool fixed;

public:
    /// Constructor
    GArray(int PreAlloc = 0)
    {
        p = 0;
        len = 0;
        fixed = false;

        alloc = PreAlloc;
        if (alloc)
        {
            int Bytes = sizeof(Type) * alloc;
            p = (Type*) malloc(Bytes);
            if (p)
            {
                memset(p, 0, Bytes);
            }
            else
            {
                alloc = 0;
            }
        }
    }

    /// Destructor  
    ~GArray()
    {
        Length(0);
    }   

    /// Returns the number of used entries
    uint32 Length() const
    {
        return len;
    }

    /// Sets the length of available entries
    bool Length(uint32 i)
    {
        if (i > 0)
        {
            if (i > len && fixed)
                return false;

            uint nalloc = alloc;
            if (i < len)
            {
                // Shrinking
            }
            else
            {
                // Expanding
                int b;
                for (b = 4; (1 << b) < i; b++)
                    ;
                nalloc = 1 << b;
                LgiAssert(nalloc >= i);
            }

            if (nalloc != alloc)
            {
                Type *np = (Type*)malloc(sizeof(Type) * nalloc);
                if (!np)
                {
                    return false;
                }

                if (p)
                {
                    // copy across common elements
                    memcpy(np, p, min(len, i) * sizeof(Type));
                    free(p);
                }
                p = np;
                alloc = nalloc;
            }

            if (i > len)
            {
                // zero new elements
                memset(p + len, 0, sizeof(Type) * (i - len));
            }

            len = i;
        }
        else
        {
            if (p)
            {
                int Length = len;
                for (uint i=0; i<Length; i++)
                {
                    p[i].~Type();
                }
                free(p);
                p = 0;
            }
            len = alloc = 0;
        }

        return true;
    }

    GArray<Type> &operator =(const GArray<Type> &a)
    {
        Length(a.Length());
        if (p && a.p)
        {
            for (int i=0; i<len; i++)
            {
                p[i] = a.p[i];
            }
        }
        return *this;
    }

    /// \brief Returns a reference a given entry.
    ///
    /// If the entry is off the end of the array and "fixed" is false,
    /// it will grow to make it valid.
    Type &operator [](uint32 i)
    {
        static Type t;
        if
        (
            i < 0
            ||
            (fixed && i >= len)
        )
        {
            ZeroObj(t);
            return t;
        }

        #if 0
        if (i > 15000000)
        {
            #if defined(_DEBUG) && defined(_MSC_VER)
            LgiAssert(0);
            #endif

            ZeroObj(t);
            return t;
        }
        #endif

        if (i >= alloc)
        {
            // increase array length
            uint nalloc = max(alloc, GARRAY_MIN_SIZE);
            while (nalloc <= i)
            {
                nalloc <<= 1;
            }

            // alloc new array
            Type *np = (Type*) malloc(sizeof(Type) * nalloc);
            if (np)
            {
                // clear new cells
                memset(np + len, 0, (nalloc - len) * sizeof(Type));
                if (p)
                {
                    // copy across old cells
                    memcpy(np, p, len * sizeof(Type));

                    // clear old array
                    free(p);
                }

                // new values
                p = np;
                alloc = nalloc;
            }
            else
            {
                static Type *t = 0;
                return *t;
            }
        }

        // adjust length of the the array
        if (i + 1 > len)
        {
            len = i + 1;
        }

        return p[i];
    }

    /// Delete all the entries as if they are pointers to objects
    void DeleteObjects()
    {
        for (uint i=0; i<len; i++)
        {
            DeleteObj(p[i]);
        }
        Length(0);
    }

    /// Delete all the entries as if they are pointers to arrays
    void DeleteArrays()
    {
        for (int i=0; i<len; i++)
        {
            DeleteArray(p[i]);
        }
        Length(0);
    }

    /// Find the index of entry 'n'
    int IndexOf(Type n)
    {
        for (uint i=0; i<len; i++)
        {
            if (p[i] == n) return i;
        }

        return -1;
    }

    /// Returns true if the item 'n' is in the array
    bool HasItem(Type n)
    {
        return IndexOf(n) >= 0;
    }

    /// Deletes an entry
    bool DeleteAt
    (
        /// The index of the entry to delete
        uint Index,
        /// true if the order of the array matters, otherwise false.
        bool Ordered = false
    )
    {
        if (p && Index >= 0 && Index < len)
        {
            // Delete the object
            p[Index].~Type();

            // Move the memory up
            if (Index < len - 1)
            {
                if (Ordered)
                {
                    memmove(p + Index, p + Index + 1, (len - Index - 1) * sizeof(Type) );
                }
                else
                {
                    p[Index] = p[len-1];
                }
            }

            // Adjust length
            len--;
            return true;
        }

        return false;
    }

    /// Deletes the entry 'n'
    bool Delete
    (
        /// The value of the entry to delete
        Type n,
        /// true if the order of the array matters, otherwise false.
        bool Ordered = false
    )
    {
        int i = IndexOf(n);
        if (p && i >= 0)
        {
            return DeleteAt(i, Ordered);
        }

        return false;
    }

    /// Appends an element
    void Add
    (
        /// Item to insert
        const Type &n
    )
    {
        (*this)[len] = n;
    }

    /// Appends multiple elements
    void Add
    (
        /// Items to insert
        Type *s,
        /// Length of array
        int count

    )
    {
        if (!s || count < 1)
            return;

        int i = len;
        Length(len + count);
        Type *d = p + i;
        while (count--)
        {
            *d++ = *s++;
        }
    }

    /// Inserts an element into the array
    bool AddAt
    (
        /// Item to insert before
        int Index,
        /// Item to insert
        Type n
    )
    {
        // Make room
        if (Length(len + 1))
        {
            if (Index < len - 1)
            {
                // Shift elements after insert point up one
                memmove(p + Index + 1, p + Index, (len - Index - 1) * sizeof(Type) );
            }
            else if (Index >= len)
            {
                // Add at the end, not after the end...
                Index = len - 1;
            }

            // Insert item
            p[Index] = n;

            return true;
        }

        return false;
    }

    /// Sorts the array
    void Sort(int (*Compare)(Type*, Type*))
    {
        typedef int (*qsort_compare)(const void *, const void *);
        qsort(p, len, sizeof(Type), (qsort_compare)Compare);
    }

    /// \returns a reference to a new object on the end of the array
    Type &New()
    {
        return (*this)[len];
    }

    /// Returns the memory held by the array and sets itself to empty
    Type *Release()
    {
        Type *Ptr = p;
        p = 0;
        len = alloc = 0;
        return Ptr;
    }
};

我在 EXE 中的几个地方重复使用了这段代码。但是,当我在一个特定文件中使用它时,我开始出现重复的符号链接(symbolic link)错误:

2>lgi8d.lib(Lgi8d.dll) : error LNK2005: "public: int __thiscall GArray<char *>::Length(void)" (?Length@?$GArray@PAD@@QAEHXZ) already defined in FrameStore.obj
2>D:\Home\matthew\network_camera\src\vod_test\Debug\vod_test.exe : fatal error LNK1169: one or more multiply defined symbols found

我在 EXE 的其他文件中使用了相同的类,没有出现错误。例如在 Camera.cpp 中我有:

void DeleteFromArray(GArray<char> &a, int Start, int Len)
{
    assert(Len >= 0);

    int64 StartTs = LgiCurrentTime();

    int Del = min(Len, a.Length() - Start);
    if (Del > 0)
    {
        int Remain = a.Length() - Start - Del;
        if (Remain > 0)
        {
            memmove(&a[Start], &a[Start+Del], Remain);
            MoveBytes += Remain;
            a.Length(Start+Remain);
        }
        else a.Length(Start);
    }

    int64 End = LgiCurrentTime();
    DeleteTime += End - StartTs;
}

编译和链接没问题...但是在 FrameStore.cpp 中:

void Scan()
{
    if (!Init)
    {
        Init = true;
        GAutoString Path = FrameFile::GetPath();
        GAutoPtr<GDirectory> Dir(FileDev->GetDir());
        GArray<char*> k;

        int64 Size = 0;
        for (bool b = Dir->First(Path); b; b = Dir->Next())
        {
            if (!Dir->IsDir())
            {
                char *e = LgiGetExtension(Dir->GetName());
                if (e && !stricmp(e, "mjv"))
                {
                    char p[MAX_PATH];
                    Dir->Path(p, sizeof(p));
                    k.Add(NewStr(p));
                    Size += Dir->GetSize();
                }
            }
        }

        GAutoPtr<Prog> p(new Prog(Size));
        for (int i=0; i<k.Length(); i++)
        {
            Files.Add(new FrameFile(k[i], p));
        }

        k.DeleteArrays();
    }
}

导致其中包含“k.Length()”的行出现链接错误...如果我注释掉它链接!然而,我在同一代码中使用 GArray 类中的其他方法,它们不会导致问题。

为什么完全在 header 中定义的模板类首先会遇到这个问题?

最佳答案

问题:

在 Lgi.dll 中定义了另一个导出 GArray 实例化的类。

#ifdef LGI_DLL
    #define LgiClass        __declspec(dllexport)
#else
    #define LgiClass        __declspec(dllimport)
#endif

class LgiClass GToken : public GArray<char*>
{
    /// stuff...
};

解决方法:

在我的 EXE 中包含该 GToken header ,特别是使用 GArray 实现的 FrameStore.cpp 文件,然后编译将从 DLL 导入这些符号而不是复制它们。

如果编译器能给我更多关于 DLL 在哪里定义符号的提示,那就太好了。简单地说“某处有重复项”不是很有帮助。

关于C++使用 header 定义的模板类乘以定义的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/754521/

相关文章:

c++ - 找出非常大数的除法模

c++ - 已经特化类的成员函数特化

c++ - VS2005 和 VS2008 的并排 list 问题

visual-studio-2005 - 您可以将 Visual Studio 的 "smart indent"设置为不删除空行中的制表符吗?

visual-studio-2005 - Visual Studio中的项目生成错误

c++ - 在容器中存储 boost::function 对象

c++ - QThread不会退出

c++ - 在 Visual Studio C++ 中跳过 else 语句?

C++放置 'const'麻烦。

C++ 无法从模板化方法中调用方法(使用模板)