user1018517
user1018517

Reputation:

headers and cpp files

I got this super simple code I'm trying to compile under Linux (first time working under linux) I programmed with c++ before and I understand the concept of headers and cpp files...

Sentence.h

#ifndef SENTENCE_H_
#define SENTENCE_H_

std::vector<std::string> split(char sentence[]);
void printWords(std::vector<std::string> words);

#endif

Sentence.cpp

#include "../include/Sentence.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

std::vector<std::string> split(char sentence[]) {
    string str(sentence);
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream

    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

void printWords(std::vector<std::string> words) {
    for (size_t i = 0; i < words.size(); ++i)
           std::cout << words[i] << endl;
}

And I'm getting those few errors which I can't figure out why...

daniel@daniel-ubuntu-server:~/workspace/HW1$ make
g++ -g -Wall -Weffc++ -c -Linclude -o bin/Sentence.o src/Sentence.cpp
In file included from src/Sentence.cpp:1:0:
src/../include/Sentence.h:4:6: error: ‘vector’ in namespace ‘std’ does not name a template type
 std::vector<std::string> split(char sentence[]);
      ^
src/../include/Sentence.h:5:22: error: variable or field ‘printWords’ declared void
 void printWords(std::vector<std::string> words);
                      ^
src/../include/Sentence.h:5:17: error: ‘vector’ is not a member of ‘std’
 void printWords(std::vector<std::string> words);
                 ^
src/../include/Sentence.h:5:29: error: ‘string’ is not a member of ‘std’
 void printWords(std::vector<std::string> words);
                             ^
src/../include/Sentence.h:5:42: error: ‘words’ was not declared in this scope
 void printWords(std::vector<std::string> words);
                                          ^
makefile:10: recipe for target 'bin/Sentence.o' failed
make: *** [bin/Sentence.o] Error 1

Upvotes: 2

Views: 746

Answers (2)

SilverCorvus
SilverCorvus

Reputation: 3076

Your header uses the std::vector class, but the vector class code is never included in it. Add #include <vector> to the header file so the class will be loaded before the rest of Sentence.h.

This will also help in other files that might use Sentece.h, since they won't have to include the vector class by themselves.

Upvotes: 4

Neil Kirk
Neil Kirk

Reputation: 21803

Sentence.h uses std::vector but does not include <vector> header. Same situation with std::string.

Upvotes: 2

Related Questions