【问题标题】:Linking error. I don't know what I'm missing链接错误。我不知道我错过了什么
【发布时间】:2015-10-27 20:27:37
【问题描述】:

我正在从 Stroustrup 的《编程:实践与原则》第 2 版学习编程。从章。 6.3.4,我正在使用书中的以下代码并得到“架构x86_64的未定义符号”错误:

#include <iostream>
#include <vector>

using namespace std;

class Token{            //User-defined type with 2 members: Token.
    public:
        char kind;      //Member 'kind'. It has a char type.
        double value;   //Member 'value'. It has a double type.
};

Token get_token();  //Created a BLANK function of Token type to read cin input.
vector<Token> tok;  //Tokens will be placed inside vector 'tok'.    

int main() 
{
    while(cin){
        Token t= get_token();   //t from input.
        tok.push_back(t);   //Value in t is pushed back in the vector.
    }
    for(int i=0;i<tok.size();++i){  //i= 0 until less than size of vector, add 1.
        if(tok[i].kind=='*'){       //Finds '*'.
            double d=tok[i-1].value*tok[i+1].value; 
            //Evaluates object before '*', multiplied by object after it.
            //Now what?
        }
    }
}

“std_lib_facitilies.h”不能解决问题。对于函数'get_token();',我是否缺少任何链接,或者我不能将函数留空(如书中所述)?我是编程新手,任何帮助将不胜感激。我正在使用 Clang 设置为:c++11、libc++。 错误:

Undefined symbols for architecture x86_64:
  "get_token()", referenced from:
      _main in 6-5f59e7.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

【问题讨论】:

  • 我认为get_token应该实现的功能。
  • 那么你的get_token()函数在哪里?
  • 还是我不能把函数留空 -- 你没有任何函数,更别说留空了。您声明了一个函数,但没有实现它。如果您愿意,可以将函数的 实现 保留为空体(或接近空体)。 Token get_token() { return Token(); }
  • 明白。谢谢你的澄清。我希望这本书能清楚地说明这一点。另外,您是否为像我这样的 COMPLETE 新手推荐任何有关编程的书籍?我觉得这本书假设我知道一些事情。不可能我自己会想到这一点。再次感谢。
  • 没有一本书能给你经验。但有些事情应该是常识——就像这样。电脑从哪里知道你的get_token()函数?

标签: c++ linker


【解决方案1】:

您需要实现 get_token()。在您的情况下,我会尝试在构造函数中执行此操作,如下所示:

class Token            //User-defined type with 2 members: Token.
{
    public:
        Token(std::istream& inputstream)
        {
            kind << inputstream;
            value << inputstream;
        }
        char kind;      //Member 'kind'. It has a char type.
        double value;   //Member 'value'. It has a double type.
};

那么你可以写Token t(cin);而不是Token t = get_token();

但我仍然不喜欢这个实现。为了使vector&lt;Token&gt; 正常工作,它应该有一个移动构造函数。这将使您能够编写while(cin) tok.push_back(Token(cin));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-01
    • 2017-12-18
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多