为什么我在预处理器中找不到类?

时间:2013-06-27 03:09:43

标签: c++ c-preprocessor

这可能很天真,但我对cpp的预处理器感到很困惑: 我定义了一个头文件 - Node.h:

#ifndef NODE_H_
#define NODE_H_

#include<iostream>
class Node{
    friend std::ostream &operator<<(std::ostream &os, const Node & n);
    public:
        Node(const int i = -1);
    private:
        Node * next;
        int value;
    friend class List;

};
#endif

然后我在Node.cpp中定义了方法:

#include "Node.h"
using namespace std;

Node::Node(const int i):value(i), next(NULL){}

ostream& operator <<(ostream & os, const Node& n){
    return os<<"value : "<<n.value<<endl;
}

最后,我有一个test.cpp文件来检查预处理器:

#include "Node.h"
//#include <iostream>
using namespace std;

int main(){
    Node * n = new Node;
    cout<<*n;
}

然而,当我尝试使用gcc编译时,我收到以下错误:

  

/home/xuan/lib/singleLinkedList/test.cpp:6:'Node::Node(int)'undefined reference

1 个答案:

答案 0 :(得分:1)

鉴于你的文件,我跑的时候:

$ g++ test.cpp
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x2c): undefined reference to `Node::Node(int)'
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x44): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Node const&)'
/usr/lib/gcc/i686-pc-cygwin/4.5.3/../../../../i686-pc-cygwin/bin/ld: /tmp/ccM7wRNZ.o: bad reloc address 0x0 in section `.ctors'
collect2: ld returned 1 exit status

...但如果我跑:

Simon@R12043 ~/dev/test/cpp
$ g++ test.cpp node.cpp

Simon@R12043 ~/dev/test/cpp
$

因此,我认为您没有在要链接到项目中的文件中包含node.cpp。也就是说,链接器找不到Node类。