Home > Mobile >  C Some headers include each other
C Some headers include each other

Time:11-27

I can't solve next problem:

//foo.h
#ifndef FOO_H_
#define FOO_H_

#include "BAR.h"
#include "foos/foo_bazz.h"


typedef struct
{
   ...
} FOO;

// HERE I HAVE CALL `foo_baz(foo, bar);`
void
foo_bar(FOO *foo, BAR *bar);

#endif /* FOO_H_ */
//bar.h
#ifndef BAR_H_
#define BAR_H_

typedef struct
{
   ...
} BAR;

#endif /* BAR_H_ */
//foos/foo_bazz.h
#ifndef FOO_BAZZ_H_
#define FOO_BAZZ_H_

#include "FOO.h"
#include "BAR.h"

void
foo_baz(FOO *foo, BAR *bar);


#endif /* FOO_BAZZ_H_ */

so it makes error like this:

foos/foo_bazz.h: error: unknown type name ‘FOO’; did you mean ‘FOO_H_’?
   16 |     FOO *foo,
      |     ^~~~
      |     FOO_H_

I tried to remove #include "FOO.h" from foos/foo_bazz.h and add typedef struct FOO; or typedef struct FOO FOO; but it didn't make some changes...

Also i tried to make inverse - i declared function in FOO.h, but result is the same.

Help me please, thank you

CodePudding user response:

Why do you want to include foo_bazz in foo.h?

It will fail for sure. The inclusion of the foo.h in foo_bazz.h will not declare the type as it is already protected by the guards.

It makes no sense. Simply include foo_bazz.h in your .c file where you will have function and data definition. IMO X-Y problem.

CodePudding user response:

The problem is that the declaration:

void foo_baz(FOO *foo, BAR *bar);

is encountered before FOO is defined. You can solve that problem by reordering the code in foo.h thus:

#include "BAR.h"

typedef struct
{
   ...
} FOO;

#include "foos/foo_bazz.h"

void
foo_bar(FOO *foo, BAR *bar);

That said @0___________ 's solution makes more sense in most cases, including this, but it is worth understanding why/how the problem occurred rather than simply blindly fixing it.

  • Related