Search code examples
cvisual-c++windows-kernel

Dependency Header file needs to be included in c , even with Forward declaration in main header file


I have a 3 header files, foo.h, bar.h & FooBar.h. And a C-source file named bar.c.

in FooBar.h

#pragma once

#include "bar.h"

in foo.h:

#pragma once

#include "FooBar.h"

typedef struct _A
{
   char a;
}A;

in bar.h

#pragma once 

/* other includes except foo.h as including that will cause circular dependency */

typedef struct _A A; //line1 - forward-declared type

void func(A* aObj);

in bar.c

#include "foo.h" //line2
#include "bar.h"

void func(A* aObj)
{
    if('\0' == aObj->a)
        aObj->a = 'A';
}

Now in bar.c, I want to remove inclusion of foo.h, as I have already forward declared the _A in bar.h. So, when I comment that out, I am getting below error (when hovering over aObj):

pointer to incomplete class type is not allowed in function func() in bar.c where I am trying to manipulate the aObj.

And after compiling the error points to

C2037: left of 'aObj' specifies undefined struct/union '_A'.

So, how do I make sure that, I dont have to use the both:

  1. Forward declaration in bar.h (//line1 above)
  2. Include foo.h in bar.c (//line2 above)

Solution

  • Now in bar.c, I want to remove inclusion of foo.h, as I have already forward declared the _A in bar.h

    You don't want to do that, because func needs to see the definition of struct _A in order to work with it, and that definition resides in foo.h.

    So bar.c must include foo.h.