Header file link-time error mystery

I am reading "Programming Principles and Practice Using C++" by Bjarne Stroustrup. I haven't paid that much attention to separating declarations from definitions because I was concentrating on understanding what I am reading about. Now I see why it's so important to separate them (too much code in one place can get you confused). I created a project, including the following files:

Token.h // Declaration
Token.cpp // Definition
Source.cpp // int main()

I declared all the classes and member functions in Token.h, but when I try to define them in Token.cpp (Token.cpp includes Token.h) I get a link-time error.

Here's Token.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "std_lib_facilities.h" // contains some standard library stuff

class Token
{
public:
	char kind;
	double value;
	string name;
	Token() { }
	Token(char arg_char) : kind(arg_char), value(0) { }
	Token(char arg_char, double arg_value) : kind(arg_char), value(arg_value) { }
};

class Token_stream
{
private:
	bool full;
	Token buffer;
public:
	Token_stream() : full(false), buffer(0) { }
	void ignore(char arg);
	Token get();
	void putback(Token var_arg); // this is the function I try to define in Token.cpp
};


Here's Token.cpp

1
2
3
4
5
6
#include "Token.h"

void Token_stream::putback(Token var_arg)
{
	full = false;
}


Here's Source.cpp
1
2
3
4
5
6
#include "Token.cpp"

int main()
{
	return 0;
}


Here's the error message I get (I am using Microsoft Visual Studio Ultimate 2012):

1>------ Build started: Project: Writing A Program, Configuration: Debug Win32 ------
1>Token.obj : error LNK2005: "public: void __thiscall Token_stream::putback(class Token)" (?putback@Token_stream@@QAEXVToken@@@Z) already defined in Source.obj
1>C:\Users\Ben\Desktop\C++\Projects\Writing A Program\Debug\Writing A Program.exe : fatal error LNK1169: one or more multiply defined symbols found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

When I remove the definition of void Token_stream::putback() from Token.cpp the program runs.
Don't include cpp files. In source.cpp you should just include Token.h.
Thanks! Everything works perfectly now! I thought it creates a chain and I only have to include Token.cpp in Source.cpp since Token.cpp has a copy of Token.h. I had no idea that the declarations look for definitions and link them automatically.
Topic archived. No new replies allowed.