Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefinition errors in .h files

Tags:

c

//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..

like image 756
codereviewanskquestions Avatar asked Mar 25 '11 08:03

codereviewanskquestions


People also ask

How do you resolve redefinition error?

Re “How do you fix a redefinition error in C programming?”, you do that by removing the redefinition. Compilers can get confused when subjected to unexpected repetition in source code. So when they complain about it, the fix is to find and remove the repetition.

How can we avoid redefinition?

Answer: The include guards in header file in C, C++ is used to avoid compiler error i.e. redefinition of function, variable or class.

What does redefinition mean in C++?

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.

Do .h files need to be compiled?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.


1 Answers

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.

like image 72
M'vy Avatar answered Oct 03 '22 05:10

M'vy