Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefinition of struct error, I only defined it once

Tags:

c++

I really don't understand how to fix this redefinition error.

COMPILE+ERRORS

g++ main.cpp list.cpp line.cpp
In file included from list.cpp:5:0:
line.h:2:8: error: redefinition of âstruct Lineâ
line.h:2:8: error: previous definition of âstruct Lineâ

main.cpp

#include <iostream>
using namespace std;
#include "list.h"

int main() {
    int no;
    // List list;

    cout << "List Processor\n==============" << endl;
    cout << "Enter number of items : ";
    cin  >> no;

    // list.set(no);
    // list.display();
}

list.h

#include "line.h"
#define MAX_LINES 10
using namespace std;

struct List{
    private:
        struct Line line[MAX_LINES];
    public:
        void set(int no);
        void display() const;
};

line.h

#define MAX_CHARS 10
struct Line {
    private:
        int num;
        char numOfItem[MAX_CHARS + 1]; // the one is null byte
    public:
        bool set(int n, const char* str);
        void display() const;
};

list.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "list.h"
#include "line.h"

void List::set(int no) {}

void List::display() const {}

line.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "line.h"

bool Line::set(int n, const char* str) {}

void Line::display() const {}
like image 321
eveo Avatar asked Feb 23 '13 15:02

eveo


People also ask

What is redefinition error in C?

For functions, it's usually that you didn't put “inline” as the storage-class-specifier (you probably left it blank). For variables, it's probably that missing “extern”. If you get this error out of the compiler, the multiple definitions are in the same source file.

What does redefinition of variable mean?

A redefinition is an attempt to redefine the same variable, e.g.: int a = 5; int a = 6; Also. int foo(); is not a definition. It's a declaration.

Can Typedef be redefined?

Using typedef redeclaration, you can redefine a name that is a previous typedef name in the same scope to refer to the same type. For example: typedef char AChar; typedef char AChar; The typedef redeclaration feature can be enabled by any extended language level.


1 Answers

You need to put include guards in your headers.

#ifndef LIST_H_
#define LIST_H_

// List.h code

#endif
like image 93
juanchopanza Avatar answered Oct 13 '22 07:10

juanchopanza