Search code examples
c++classredefinition

Error: Redefinition of Class (C++)


I'm trying to figure out why I'm getting the following error:

error: redefinition of 'TimeDuration'

// TimeDuration.cpp

#define HOUR 3600
#define MIN 60

#include <iostream>
#include <string>
#include "TimeDuration.h"

using namespace std;

TimeDuration::TimeDuration() {
    seconds = 0;
}

void TimeDuration::setDuration(const int sec) {
    seconds = sec;
}

void TimeDuration::display() {
    // Some code to display the time
}

The error is showing in my header file.

// TimeDuration.h

class TimeDuration {
    private:
        int seconds;
    public:
        TimeDuration();                     
        void setDuration(const int sec);    
        void display();                     
};

Solution

  • The error is probably because you don't have header guards in TimeDuration.h

    A standard way to header guard is to at the beginning of the file write:

    #ifndef TIME_DURATION_H
    #define TIME_DURATION_H
    

    and at the end of the file:

    #endif