Redefinition errors in .h files
Asked Answered
I

4

11
//list.h file
typedef struct _lnode{
    struct _lnode *next;
    size_t row;
    size_t column;
    short data;
}lnode;

typedef struct _llist{
    struct _lnode *head;
    size_t size;

}llist;

//matrix.h file
typedef struct _matrix{

    size_t width;
    size_t height;
    size_t k;

    int **data;

}matrix;

//smatrix.h file
#include "list.h"
#include "matrix.h"

typedef struct _smatrix{
    size_t width;
    size_t height;
    size_t k;

    llist data;
}smatrix;

smatrix* make_smatrix(matrix *m);

smatrix.h file includes list.h file and matrix.h files. If I include those header files in smatrix.h file then I get

 redefinition of 'lnode'. redefinition of '_llist' and redefinition of '_matrix' errors.

If I took those heder files our from smatrix.h file then the error went away but it complains about matrix type in the function parameter. I want to call functions defined in list.h and matrix.h files in smatrix.c file.. What do I do? Thanks in advance..

Idempotent answered 25/3, 2011 at 8:18 Comment(0)
A
28

Possible problem of multiple inclusions.

Try to guard your header files with #ifndef read about it here

file list.h

#ifndef _LISTH_
#define _LISTH_

<your code>

#endif

file matrix.h

#ifndef _MATRIXH_
#define _MATRIXH_

<your code>

#endif

It will prevent you too have redefinitions if you have a loop in header inclusions.

Areta answered 25/3, 2011 at 8:21 Comment(0)
M
8

you need include guards in your header files.

Mucoprotein answered 25/3, 2011 at 8:20 Comment(0)
B
2

Well from your posted code what I think is missing is at the beginning of each *.h file:

#ifndef _some_unique_identifier_for_each_header 
#define _some_unique_identifier_for_each_header

...header contents

#endif //_some_unique_identifier_for_each_header

or a

#pragma once 

if your compiler supports it.

Without this, if the header is included multiple times from various sources you get errors relating to redefinition.

Barbarous answered 25/3, 2011 at 8:29 Comment(0)
L
1

You probably include smatrix.h and list.h in some other file. You should avoid that. The usual way to do that is to use include guards.

These are macros that you check with #ifdef at the beginning of the file (with #endif in the end), and #define them inside the #ifdef ... #endif, thus insuring that even if you do include the same file multiple times, the compiler will only read it once, at the first time, and skip all the rest.

Leisure answered 25/3, 2011 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.