Overriding errors in .h files

//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); 

The smatrix.h file contains the list.h and matrix.h files. If I include these header files in the smatrix.h file, I get

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

If I took these heder files from the smatrix.h file, then the error disappeared, but it complains about the type of matrix in the function parameter. I want to call the functions defined in the list.h and matrix.h files in the smatrix.c file. What should I do? Thanks in advance.

+7
source share
4 answers

There may be a multiple inclusion problem.

Try protecting your header files with #ifndef read about it here

file list.h

 #ifndef _LISTH_ #define _LISTH_ <your code> #endif 

matrix.h file

 #ifndef _MATRIXH_ #define _MATRIXH_ <your code> #endif 

It will also prevent overrides if you have a loop in the headers.

+18
source
+8
source

Well, from your published code, what I think is missing is at the beginning of every * .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

 #pragma once 

if your compiler supports it.

Without this, if the title is included several times from different sources, you get errors related to overriding.

+2
source

You probably included smatrix.h and list.h in another file. You should avoid this. The usual way to do this is to use include guards .

These are macros that you check with #ifdef at the beginning of the file (with #endif at the end) and #define inside #ifdef ... #endif , thereby ensuring that even if you include the same file several times, the compiler will only read him once, for the first time and will miss the rest.

+1
source

All Articles