【问题标题】:How to compile a templated class (C++) in Eclipse?如何在 Eclipse 中编译模板类(C++)?
【发布时间】:2012-01-29 17:46:22
【问题描述】:

我正在尝试在 Eclipse 中创建一个链表类,但无法正确编译。

这是我的 .cc 文件(代码片段)

#include <iostream>
#include "list.h"

using namespace std;

template <class T>
bool List<T>::isEmpty()
{
    return (firstNode == NULL);
}

这是我的 list.h 文件(代码片段)

#ifndef __LIST_H__
#define __LIST_H__

template <typename T>
class List {

public:

    bool isEmpty();

 private:
    struct node {
    node   *following;
    node   *previous;
    T      *contents;
    };

    node   *firstNode;
};

#include "list.cc"

#endif /* __LIST_H__ */

我在 Eclipse 中尝试“Building All”,但出现以下错误:

make all 
Building file: ../list.cc
Invoking: Cross G++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"list.d" -MT"list.d" -o "list.o"     "../list.cc"
../list.cc:13: error: redefinition of 'bool List<T>::isEmpty()'
../list.cc:13: error: 'bool List<T>::isEmpty()' previously declared here
make: *** [list.o] Error 1

请帮忙...谢谢。我很乐意提供任何需要的说明

编辑:我得到了 .h 文件,所以我知道它是正确的。我也知道我应该有一个名为 list.cc 的 .cc 文件(它包含在 .h 文件的末尾)

【问题讨论】:

标签: c++ eclipse compilation


【解决方案1】:

您需要随实现更改文件的扩展名。

编译器将处理此文件进行编译,并将处理两次,因为您将它包含在标头中。

您的文件如下所示:

#include <iostream>
#include "list.h"

using namespace std;

template <class T>
bool List<T>::isEmpty()
{
    return (firstNode == NULL);
}

将会变成

#include <iostream>
#ifndef __DLIST_H__
#define __DLIST_H__

template <typename T>
class List {

public:

    bool isEmpty();

 private:
    struct node {
    node   *following;
    node   *previous;
    T      *contents;
    };

    node   *firstNode;
};

#include "dlist.cc"

#endif /* __DLIST_H__ */

using namespace std;

template <class T>
bool List<T>::isEmpty()
{
    return (firstNode == NULL);
}

这又会变成

#include <iostream>
#ifndef __DLIST_H__
#define __DLIST_H__

template <typename T>
class List {

public:

    bool isEmpty();

 private:
    struct node {
    node   *following;
    node   *previous;
    T      *contents;
    };

    node   *firstNode;
};

template <class T>
bool List<T>::isEmpty()
{
    return (firstNode == NULL);
}

#endif /* __DLIST_H__ */

using namespace std;

template <class T>
bool List<T>::isEmpty()
{
    return (firstNode == NULL);
}

所以函数isEmpty()被定义了两次。

将文件重命名为dlist.impl

【讨论】:

  • 我想通了。我需要告诉 eclipse 从构建中排除 list.cc,因为它隐式包含在 .h 文件中。不过我还是给你最好的答案
  • @Nosrettap 这实际上是我指出的原因。此外,您可能还应该重命名该文件。常见的扩展名是.impl,你应该坚持下去。
  • @Nosrettap cc 等价于 cpp,因为 hpp 等价于 h。
【解决方案2】:

尝试将List&lt;T&gt;::isEmpty() 的定义放在与声明类相同的文件中。

【讨论】:

  • 这确实解决了问题,但并没有解决原因。看看我的回答。
  • 你是对的,我应该提供一个更详细的原因来解释它发生的原因。我也给你投票了。
【解决方案3】:

鉴于您提供的标头格式不寻常,要对其进行测试,您将需要另一个源文件。从新的源文件(比如 test.cpp)开始,只需 #include "list.h",它将检查任何语法错误,但不会实例化您的 List 模板。

(只编译test.cpp,而不是list.cc,因为list.cc间接包含在test.cpp中)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2012-04-20
    • 2015-07-31
    • 2011-03-04
    相关资源
    最近更新 更多