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 n开发者_如何学Cow 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?
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.
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
Header file 1:
#ifndef HEADERFILE1_H
#define HEADERFILE1_H
//...
#endif
Header file 2:
#ifndef HEADERFILE2_H
#define HEADERFILE2_H
#include "headerfile1.h"
//...
#endif
精彩评论