Linking/namespace error

I am having this error message:

1
2
3
4
5
 pserver.o: In function `tempSpace::nextPrime(int)':
pserver.cpp:(.text+0x0): multiple definition of `tempSpace::nextPrime(int)'
sim.o:sim.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [passServer] Error 1


I am thinking that it has something to do with the namespace I am using, or possibly what and where I am including my header files, so I am going to post the code fragments of those (sorry if this is hard to follow):

here is my make file:
1
2
3
4
5
6
7
8
9
10
11
passServer : sim.o pserver.o
        g++ -o passServer sim.o pserver.o -Wall

sim.o : sim.cpp pserver.o
        g++ -c sim.cpp -Wall

pserver.o : pserver.cpp hashmap.hpp hashmap.h
        g++ -c pserver.cpp -Wall

clean : 
        rm *.o



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//hashmap.h

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

using namespace std;
namespace tempSpace{

template <typename K, typename V>
class myHashMap {
.
.
.
};

#include "hashmap.hpp"
} //end namespace


1
2
3
4
5
6
7
8
9
10
11
12
//hashmap.hpp
using namespace tempSpace;

int nextPrime(int n);

int nextPrime(int n)
{
//find prime
}

//defining myHashMap functions



1
2
3
4
5
6
7
8
9
10
11
//pserver.h
#include "hashmap.h"
#include <string>

using namespace tempSpace;

template<typename K, typename V>
class myPserver {
.
.
};

1
2
3
4
5
6
7
//pserver.cpp
#include <iostream>
#include <string>

using namespace std;
#include "pserver.h"

1
2
3
4
5
6
//sim.cpp
#include "pserver.h"

using namespace std;

//stuff 


So, the error message suggests that I am defining nextPrime(int) multiple times, BUT the declaration and definition are in hashmap.hpp ONLY. It does not exist in any other files. So why does the compiler think that I am defining it multiple times?


Last edited on
The definition of nextPrime will appear everywhere you include hashmap.hpp, as so everywhere you include hashmap.h ( since it includes hashmap.hpp.
You should either decalre it as inline or move its definition in a source file ( the latter is better )
Well, sim.cpp includes pserver.h which includes hasmap.h which includes hashmap.hpp which defines the function. pserver.cpp does the same, so you get the function defined in both sim.cpp and pserver.cpp.
The thing to do here would be not to define functions (unless they are templates (or inline if I recall correctly) ) in headers.
Protect your header files so they can only be copied once, after that all other includes will be ignored (which is what you want)
1
2
3
4
#ifndef _CLASSES_OR_NAMESPACES_H
#define _CLASSES_OR_NAMESPACES_H
//put classes or namespaces here
#endif 
That won't work if the header will be included in multiple source files. It will still cause multiple definitions
Topic archived. No new replies allowed.