3

我已经在标头中声明了静态 const 数组,然后在 cpp 文件中实现了它,但我无法弄清楚发生了什么。

子系统.h:

#ifndef _SUBSYS_H
#define _SUBSYS_H

namespace Engines
{

    namespace Particles
    {

        class SubSys : public ISubSys
        {

        private:
            static const int _M[ 3 ];
            ...
            //rest of class
        };

    }

}

#endif

子系统.cpp:

#include "Subsys.h"

namespace Engines
{

    namespace Particles
    {

        const int SubSys::_M[ 3 ] = 
        {
            0x80,
            0x7f,
            0x01
        };

    }

}

错误 LNK2001:未解析的外部符号“private static int const * const Engines::Particles::SubSys::_M”(?_M@SubSys@Particles@Engines@@0QBIB)

如果我在类外部的标头中实现数组,我不会在使用静态库的应用程序中得到 LNK2001 错误。我在编译静态库时确实得到了 LNK4006(即多次添加符号)。

我还删除了 .cpp 文件中的命名空间,并使用了完整的 Engines::Particles::SubSys::_M 名称。出现同样的问题。

4

1 回答 1

1

感谢您的所有帮助,但它并没有完全回答我的问题,即在库本身中使用 cpp 文件,而不是将初始化移动到调用库的应用程序中的 cpp 文件中。

我使用 VC++解决它的方法是使用库中的另一个头文件。该头文件包含所需的所有静态初始化程序。然后我只是在应用程序的库中#include 那个头文件,它就可以工作了。

完整的设计是:

子系统.h

#ifndef _SUBSYS_H
#define _SUBSYS_H

namespace Engines
{

    namespace Particles
    {

        class SubSys : public ISubSys
        {

        private:
            static const int _M[ 3 ];
            ...
            //rest of class
        };

    }

}

#endif

SubsysParticlesInit.h

#ifndef _SUBSYS_PARTICLES_INIT_H
#define

#include "Subsys.h"

namespace Engines
{
    namespace Particles
    {
        const int SubSys::_M[ 3 ] = 
        {
            0x80,
            0x7f,
            0x01
        };
    }
}

#endif

应用程序.cpp

#include "Subsys.h"
#include "SubsysParticlesInit.h"

    int main() { ... }

它需要从应用程序调用 2 个标头而不是 1 个,但至少所有代码都包含在库中。

于 2011-11-13T23:55:28.697 回答