Django
Django

Reputation: 415

struct in header file 1 needed in header file 2, how do I do that?

I have a struct that I use in header file1. I now also need that struct in header file2 because it is used in function prototypes. I have included header file1 in header file2, but this give a lot of complaints of redefition of types after compiling? Is there a straightforward way to do it? I have googled about nested header files but this gives me rather complicated articles. I was wondering if there is a simple way to do this?

Upvotes: 1

Views: 182

Answers (3)

Mike Caron
Mike Caron

Reputation: 14561

Header file 1:

#ifndef HEADERFILE1_H
#define HEADERFILE1_H

//...
#endif

Header file 2:

#ifndef HEADERFILE2_H
#define HEADERFILE2_H

#include "headerfile1.h"

//...
#endif

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

I believe your header files are not guarded with include guards to prevent redefinitions. They should be

//header.h
#ifndef SOME_LONG_UNIQUE_NAME
#define SOME_LONG_UNIQUE_NAME

//header contents here

#endif

As a side note, you don't need all the header and struct definition just to declare function arguments. A forward declaration is enough.

struct C; //not including C.h
struct C* f(struct C* p);

This decreases code coupling and accelerated compilation

Upvotes: 1

cnicutar
cnicutar

Reputation: 182734

Sure there is. Use include guards.

file1.h

#ifndef FILE1_H
#define FILE1_H

/* Define everything here. */

#endif

This way you can include file1.h over and over. In particular, you should always use include guards if a header defines things.

As a side note, if you don't need the details of the struct (that is, it should be an opaque type), you can use an incomplete type and just say struct yourstruct; at the top.

Upvotes: 3

Related Questions