在Linux上编译时未定义引用的奇怪错误

时间:2012-04-22 23:32:23

标签: c++ g++

  

可能重复:   Why can templates only be implemented in the header file?

我在Linux上编译g ++ 4.5.5时遇到以下错误,据称我的代码在Windows上运行正常。

A.o: In function `A::NewObj(int)':
A.cpp:(.text+0x39): undefined reference to `List<A>::Add(A*)'
collect2: ld returned 1 exit status
make: *** [program] Error 1

我不知道我的代码有什么问题。我不确定我是否正确地声明了对象list_A。

文件:

A.H

#ifndef A_H
#define A_H

class A
{
public:
    int key;
    A() { key=0; }
    A(int i) { key = i; }
    void NewObj(int i);
};

#endif

A.cpp

#include "A.h"
#include "List.h"

static    List<A> *list_A = new List<A>();

void A::NewObj(int i)
{
    A *nobject = new A(i);
    list_A->Add( nobject );

}

List.h

#ifndef LIST_H
#define LIST_H

template<typename Objct>
class Node
{
public:
    Objct* datapiece;
    Node *next, *previous;

    Node() { next = previous = 0; }
    Node ( Objct *object, Node *n = 0, Node *p = 0)
    {
        datapiece = object;
        next = n; previous = p;
    }
};

template<typename Objct>
class List
{
public:
    List() { head = tail = 0; }
    void Add( Objct* );
protected:
    Node<Objct> *head, *tail;
};

#endif

List.cpp

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

template<typename Objct>
void List<Objct>::Add( Objct *o )
{
    int i =5;
    Node<Objct> *nnode = new Node<Objct>(o);
    if ( o->key < i )
    std::cout << "Ok" << std::endl;
}

的main.cpp

#include <iostream>
#include "A.h"
#include "List.h"

int main()
{
    A *magazyn = new A();
    magazyn->NewObj(6);
}

生成文件

CC=g++
CFLAGS=-c -Wall -pedantic

program: List.o A.o main.o
    $(CC) List.o A.o main.o -o program
A.o: A.cpp List.h
    $(CC) $(CFLAGS) A.cpp
List.o: List.cpp
    $(CC) $(CFLAGS) List.cpp
main.o: main.cpp A.h
    $(CC) $(CFLAGS) main.cpp

1 个答案:

答案 0 :(得分:1)

问题在于,模板类List需要在每个使用它的编译单元中定义其方法。模板通常不遵循一个标头,一个实现文件规则。有关详细信息,请参阅此相关问题:Why can templates only be implemented in the header file?