Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
andirew Avatar asked Nov 16 '25 04:11

andirew


1 Answers

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
like image 63
Rostislav Avatar answered Nov 18 '25 20:11

Rostislav