andirew
andirew

Reputation: 23

Redefinition of a class in a header file

I'm attempting to compile my code with g++, but its throwing this compiler error:

Enrollment.h:3:7: error: redefinition of class sict::Enrollment
Enrollment.h:3:7: error: previous definition of class sict::Enrollment

my Enrollment.h:

namespace sict{
class Enrollment{
  private:
    char _name[31];
    char _code[11];
    int _year;
    int _semester;
    int _slot;
    bool _enrolled;
  public:
    Enrollment(const char* name , const char* code, int year, int semester ,  int time );
    Enrollment();
    void set(const char* , const char* , int ,int,  int , bool = false );

    void display(bool nameOnly = false)const;
    bool valid()const;
    void setEmpty();
    bool isEnrolled() const;
    bool hasConflict(const Enrollment &other) const; 
  };

}

Any way to fix this?

Upvotes: 2

Views: 9722

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

You need to use some include guards. Either #pragma once or:

#ifndef MY_FILE_H
#define MY_FILE_H
    ....
#endif //MY_FILE_H

This is to prevent the same code being included in every file where you include this header (double inclusion). This will essentially help out the pre-processor. More information here.

Upvotes: 3

Rostislav
Rostislav

Reputation: 3977

The problem is likely that your header file is included (directly and indirectly) in the same translation unit. You should use some way of avoiding the multiple includes of the same header file in your cpp's. I prefer #pragma once in the beginning of your header file - it is not standard but it is supported by all major compilers. Otherwise you can go for good-old include guards:

#ifndef _Enrollment_h_
#define _Enrollment_h_
// Your header contents here
#endif

or with pragma:

#pragma once
// Your header contents here

Upvotes: 11

Related Questions