【问题标题】:C++: link error with static const variables in template classC++:与模板类中的静态 const 变量链接错误
【发布时间】:2015-09-07 02:43:23
【问题描述】:

我正在开发一个接收模板类对象作为参数的类。由于它有一个模板对象,我在 .h 文件中定义所有方法(没有 .cpp)。

我在 .h 文件中声明了静态 const 变量,并在 .cpp 文件中对其进行了初始化(在我的情况下,这是 .cpp 文件的唯一用途)。我在某些方法中访问这些静态 const 变量。

我可以毫无问题地编译这个类。当我尝试在将执行它的文件中包含头文件时出现问题,然后出现以下错误:

UnitTest.obj : Error LNK2001: unresolved external symbol "public: static char const * const A::FNUMBER

我尝试在 .cpp 文件中定义方法,但是当我尝试编译时,在提到的模板类的所有方法中都出现了链接器错误。

这里是代码示例:


头文件(.h)

#ifndef A_H
#define A_H

#include "TemplateClass.h"

typedef TemplateClass<int, char> A_TemplateClass;

class A{

    public:
        static const float FNUMBER;

        //Due to I refer a template class, I have to implement all my methods in .h file,
        //else I have a lot of linker errors (1 for each template class method)
        A(A_TemplateClass &atc) : aTemplateClass(atc) {};

        void method1(){
            //Use the static const variable
            //If I do not access this variable, there is no problems.
            float f = FNUMBER + 3.2;
            [...]
        }

        void method2(){
            //Use the static const variable
            //If I do not access this variable, there is no problems.
            float f = FNUMBER + 3.3;
            [...]
        }


    private:
        A_TemplateClass aTemplateClass;

};


#endif

.cpp 文件

#include "A.h"

const float A::FNUMBER = 1.3f;

UnitTest.cpp 文件

#include "TemplateClass.h"
#include "A.h"

int main(){
    TemplateClass<int, char> x;
    A a(x);
    float f = A::FNUMBER; //Linker ERROR
    //If I delete the above line, there are no errors.
}

正如我所说,如果我不在类中使用静态 const 变量,则不会出现错误。 我做错了什么?谢谢。

【问题讨论】:

  • 您的UnitTest.cpp 是否链接到包含A::FNUMBER 定义的.cpp 文件?您可能没有将单元测试与实现文件链接起来。
  • ; 代替. 放在typedef 的末尾,并用; 终止类A - 这编译完美。
  • A_TemplateClassmethod1method2 等内容真的与手头的问题相关吗?或者您可以删除它们以创建更好的Minimal, Complete, and Verifiable example?因为按原样,这看起来不是最小的或可验证的(鉴于 Arnon Zilca 刚刚指出的语法错误)。
  • SIntax 错误已修复。实际上,在我的真实课堂上,我有 ;在课程结束时和一个;代替 。在 typedef 的末尾。如果我尝试访问静态 const 变量,method1 和 method2 仅与显示链接器错误有关。
  • 请注意,在我的情况下,类编译,只有当我尝试从 UnitTest.cpp 包含它时才会出现错误

标签: c++ templates


【解决方案1】:

您确定要使用 A.cpp/A.o 进行编译/链接吗?假设 TemplateClass.h 没有外部 .cpp 文件,您的代码应该使用 g++ UnitTest.cpp A.cpp 编译。

【讨论】:

  • 我确定 TemplateClass 没有 .cpp 文件。我正在使用 Visual Studio 进行编译。
  • 我所有的方法实现都在.h文件中,问题可能是链接器没有搜索.cpp文件中的static const变量定义?
  • 我已将#include "A.cpp" 添加到 UnitTest.cpp 文件中,现在一切正常。我不明白为什么我需要添加 include。有什么办法可以避免吗?
  • 我猜你没有编译A.cpp文件或者你没有链接A.obj文件。
  • 我建议不要包含 .cpp 文件。我认为这是不好的做法。最好通过将 A.cpp 添加到源来修复您的构建命令。
【解决方案2】:

包括.cpp 文件,其中包含static const 变量初始化,问题就解决了。

【讨论】:

  • 那么听起来你肯定没有链接。你应该按照我和 weavr 的建议去做:链接你的编译文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
相关资源
最近更新 更多