【问题标题】:c++ undefined symbol when compilingc++编译时未定义符号
【发布时间】:2013-03-07 09:04:33
【问题描述】:

已修复:头文件中有两次该方法

尝试编译我的项目时出现以下错误

% make
g++ -o p4 testTree.o tree.o node.o check.o
Undefined                       first referenced
 symbol                             in file
Tree::inTree(int)                   tree.o
ld: fatal: Symbol referencing errors. No output written to p4
collect2: ld returned 1 exit status
*** Error code 1
make: Fatal error: Command failed for target `p4'

生成文件

p4: testTree.o tree.o node.o check.o
    g++ -o p4 testTree.o tree.o node.o check.o
testTree.o: testTree.cc tree.h node.h check.h
    g++ -c -Wall -Werror testTree.cc

tree.o: tree.h tree.cc node.h check.h
    g++ -c -Wall -Werror tree.cc
node.o: node.h node.cc check.h
    g++ -c -Wall -Werror node.cc
check.o: check.h check.cc
    g++ -c -Wall -Werror check.cc
clean:
    rm -f *~ *.o p4

tree.cc 和 tree.h 中的相关代码:

tree.cc

...
bool Tree::inTree(int k) const
{
     return locate(k,root) != NULL;
}
...

tree.h

#ifndef TREE_H
#define TREE_H

#include "node.h"
#include "check.h"
using namespace std;
class Tree
{
  private:
    Node *root;
  public:
    Tree();
    Tree(const Tree & t);
    const Tree & operator=(const Tree &t);
    friend ostream & operator<<(ostream &out, const Tree &t);
    bool inTree(int k) const;
    double & operator[](int k);
    double & operator[](int k) const;
    ~Tree();
    bool inTree(int index);
  private:
    Node * locate(int k, Node *rt) const;
    ostream & display(ostream &out, Node *r, int dir=Node::L) const;
    void add(int k, Node*&r);
    void kill(Node *&rt);
    void copy(Node *rt, Node *&newRt);
};
#endif

我觉得这很简单,但我似乎无法弄清楚。

【问题讨论】:

  • 为什么inTree在.h文件中声明了两次? :v(一个常量和一个非常量)
  • 哦,笨蛋。让我解决这个问题
  • 是的,这就是错误。谢谢一堆。这就是我将函数声明从一个文件复制到另一个文件的结果......
  • 一直发生,除了我的情况,通常是整个类:p

标签: c++ compiler-errors makefile undefined-symbol


【解决方案1】:

您收到的消息实际上来自链接器,而不是来自编译器。

您的一个成员函数 bool Tree::inTree(int index); 已正确声明并定义为 const 成员函数:

 // Declaration in tree.h
 bool inTree(int index) const;

 // Definition in tree.cc
 bool Tree::inTree(int k) const
 //                       ^^^^^

但是,在tree.h 中,您还定义了inTree() 的非const 重载:

// Declaration in tree.h, definition (supposedly) nowhere
bool Tree::inTree(int k)

没有提供定义。这就是链接器所抱怨的。

【讨论】:

  • 我已经声明了两次,一次使用 (int k),一次使用 (int index)。感谢您的帮助。
  • @Dazedy:问题是不是您用不同的参数名称声明了两次。参数名称无关紧要。问题是在一种情况下您使用了const 限定符,而在另一种情况下您没有使用。
  • 嗯。因此,如果没有该 const,它是否会根据变量名而重载,而不仅仅是参数的数量/类型?
  • @Dazedy:不,你会有两个完全相同的成员函数的声明——编译器会拒绝它。参数名称无关紧要,只有参数 types 决定函数的签名。
【解决方案2】:

这是你的错误:

bool Tree::inTree(int k) const
{
 return locate(k,root) != NULL;
}

在您定义的.h

bool inTree(int);

这是不同的!

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 2015-05-23
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多