C++ Error message redefinition of functions

Hayden Coyle picture Hayden Coyle · Nov 13, 2013 · Viewed 29.7k times · Source

I am using two stacks to implement a queue class. My header file looks like:

#ifndef _MyQueue_h
#define _MyQueue_h
using namespace std;

template <typename T>
class MyQueue {

public:
    MyQueue();
    ~MyQueue();
    void enqueue(T element);
    T peek();
    void dequeue();
    int size();
    bool empty();

private:
    int count;
    stack<T> stk1;
    stack<T> stk2;
};
# include "MyQueue.cpp"
# endif

And my cpp (implementation) file looks like:

#include <stack>
#include "MyQueue.h"
using namespace std;

template <typename T>
MyQueue<T>::MyQueue()
{
    count = 0;
}

template <typename T>
MyQueue<T>::~ MyQueue()
{
}

template <typename T>
void MyQueue<T>::enqueue(T element)
{
    stk1.push(element);
    count ++;
}

(other functions omitted).

However, using Xcode 4.5, it keeps saying that my functions (MyQueue, ~MyQueue, enqueue, peek, etc.) are redefined. Can anyone help me to clarify where have I redefined them?

Thank you

Answer

john picture john · Nov 13, 2013

You're trying something which I really don't like. It's a pretence.

Remove #include "MyQueue.cpp", replace it with the content of MyQueue.cpp, delete the file MyQueue.cpp. Now everything will work.

You are trying to pretend the template code can be split into header file and implementation file. But because it can't you have to cheat by including the implementation file in the header file. It's less confusing if you don't cheat or pretend and just have one file, the header file, with everything in it.

The precise reason that you get a redefinition is that you are compiling your cpp file, which includes your header file, which includes your cpp file again. So the content of the cpp file gets compiled twice.