Multiple definition error

I have this work, and finally finished it with only a header. I have to have .cpp and .h files. However when I try to split my header, I get the following error. Original file runs without any problems as it is, but I really need both .cpp and .h files.

error: it says multiple definition of root and its first declaration is at test.o file, however there are no 'root' string in my test file

1
2
3
4
5
Trie.o:(.bss+0x0): multiple definition of `root'
test.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
makefile:6: recipe for target 'test' failed
make: *** [test] Error 1 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef TRIE_H
#define TRIE_H

#include <iostream>
#include <cstring>
using namespace std;
// define character size
#define CHAR_SIZE 128
int root = 0;

// A Class representing a Trie node
class Trie
{
public:
	bool isLeaf;
	char key;
	double val;
	Trie* character[CHAR_SIZE];

	Trie();
	Trie(char, double);
	void remove(Trie*);
	~Trie();
	bool add(pair<string, double>);
	bool haveChildren();
	unsigned int numLeaves();
	unsigned int numNodes();
	unsigned int numN();
	void printTrie();
	double search(string);
};

#endif 
Last edited on

however there are no 'root' string in my test file

Yes there is. Your test file includes that header, so your test file contains int root = 0;

#include is copy-pasting a header into wherever you wrote #include. As if you typed in the whole header file yourself. So everywhere you have #included this header file, you have written this: int root = 0;

So how many cpp files contain int root = 0;? How many times have you tried to create the exact same object, root, in your program? You're only allowed to create the exact same object ONCE in a program.



While I'm here, putting using namespace std; anywhere is bad practice, and putting it in a header file will get you beaten up in the car park by anyone who has to work with your code.
Last edited on
Repeater thanks for reply. I forgot to comment out int root = 0; line. After commenting that out, it worked.
Topic archived. No new replies allowed.