0

我正在尝试将单独的文件链接/引用在一起进行编译。我以前从未这样做过,所以我迷失了这个错误。好像我已经引用了我需要的东西。

我有三个文件,main.cpp、parser.cpp 和 header.h Main 调用 parser 来解析文本(尽管我还无法测试它是否真的有效:l)

main.cpp -

#include "header.h"

using namespace std; // I know this isn't recommended, I'm changing this later.

        int main(){
    string input, arg1, arg2;
    vector<string> parsedIn;
    cout << "<";
    while(getline(cin, input)){


            parsedIn = parser(input);
            //more code, this is the only call to parser and compile error 
            //stops here

解析器.cpp -

#include "header.h"

std::vector<std::string> parser(std::string &input){
int i=0;
//int begin=1;
int  count=0;
std::vector<std::string> parsedIn;

        while(i<input.length()){

                char temp = input.at(i);
                if(temp != ' '){
                parsedIn[count] += temp;
                count++;
                }
        i++;
        }

        if(count < 3)
        parsedIn[0] = "Error"; // Set first value to "Error" to report an input issue

return parsedIn;
}

头文件.h

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>

std::vector<std::string> parser(std::string &input);

我知道我也应该使用警卫,但我的 TA 并不清楚我是如何设置这些的……不过是婴儿步骤。这是我第一次使用 C++,所以我想弄清楚为什么没有引用它。

当然,错误是对解析器的未定义引用。

编辑:我对代码进行了更改以反映我根据您的建议所做的事情。

具体来说 parse(std::string &input) 已经变成了 parser(std::string &input)

4

3 回答 3

7

parser.cpp 的“parser”方法拼写为“parse”,但你的 header.h 说它被命名为“parser”。

于 2013-09-09T22:52:22.027 回答
3

你还有一个问题。

std::vector<std::string> parsedIn;
// ...
parsedIn[count] += temp;

向量的大小为parsedIn0。[]在空向量上使用会导致未定义的行为。您需要执行push_back操作以将元素添加到向量。与std::map容器不同,您不能使用[]运算符将​​元素添加到向量中。

于 2013-09-09T22:52:40.543 回答
0

您无法链接您的文件。

小步骤:

1)写helloWorld如果你还没有。可以调用源文件hello.cpp

2)而不是从源代码到可执行文件一步构建,如下所示:

g++ hello.cpp

尝试构建目标文件, hello.o,然后从中构建可执行文件:

g++ -c hello.cpp -o hello.o
g++ hello.o -o hello

3) 添加一些小函数,调用它void foo(),它不接受任何参数,不返回任何内容,打印出一些东西并且什么都不做。将其放入并在hello.cpp完美运行之前不要继续。

4) 移动foo()到它自己的源文件(foo.cpp)和头文件(foo.h)。现在不要担心头球后卫。像这样编译和构建:

g++ -c hello.cpp -o hello.o
g++ -c foo.cpp -o foo.o
g++ hello.o foo.o -o hello

如果你走到这一步,你已经做得很好了。

于 2013-09-10T01:42:25.150 回答