1

I have 2 header files. My code is similar to the following:

file1.h

#include "file2.h"

struct foo{
   int one;
};

//compiles if I add the following line.
//struct bar;

void dosomething(bar* param);
foo* dosomething1();

file2.h

#include "file1.h"

struct bar{
   int two;
   struct foo* two;
};

//also error in compilation time unless I add the following
//struct foo;
void dostuff(foo* param);

Why is it yielding does not name a type "bar" error in file1.h. I thought by including file2.h, bar* would be defined just like foo* and vice versa.

2
  • Please confirm the compiler settings you're using. Are you compiling this as C or C++? And if so, what version? Commented May 25, 2015 at 1:12
  • g++ -g -O0 -Wall -Wextra -std=gnu++11 Commented May 25, 2015 at 1:16

1 Answer 1

1

header files should have include guards, to protect against circular include.

circular dependencies can be broken using forward declarations, like you wrote:

struct bar;

this is because an #include directive is just an instruction to the preprocessor to substitute text

this means that the second time in the circular include the preprocessor tries to include a file, the include guard will stop it, and thus the first time the compiler sees file1.h, it has not yet seen file2.h

Sign up to request clarification or add additional context in comments.

7 Comments

why doesn't it work If I try to use forward declaration in file2.h by adding struct foo; before declaring struct bar. and put foo* foopointer; inside bar? It works however with just struct foo* foopointer; inside bar.
In the file you are breaking circular dependency using struct xxx; you should not include the other file. The easiest way to figure out what's happening here is to compile with -E and read the result of preprocessing
I shouldn't include the header file in the header files, like include file1 in file2? So do I include them in the cpp files instead?
In at least one of the header-files you need to break the circular dependency using a forward declaration. In that file you should only have the forward declaration, not the include of the other file.
Thanks! No, it's not a bad post. And down-voting without leaving a comment on how the post can be improved is frowned upon.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.