Search code examples
c++typescompilationincludecyclic-dependency

C++ Errors: " 'class' does not name a type" and "invalid use of incomplete type ‘struct ...' "


Here is a very repetitive issue, also here in StackOverflow, but I do not manage to solve my problem even trying the different answers. So, I have some classes:

main.cpp:

#include "foo.h"
#include "bar.h"

...

foo.h:

#include "bar.h"
class foo {
  foo();
  bar& bind(bar &b);
  gru& bind(gru &g);
};

bar.h:

#include "foo.h"
class bar {
  bar();
  foo& bind(foo &f);
  gru& bind(gru &g);
};

Clearly, I have a cyclic dependency. So I get the infamous error 'bar' does not name a type. In this case, I add class bar; to foo declaration and delete the #include. When I do that, I get: invalid use of incomplete type ‘struct bar'.

I tried in some different ways, also adding class foo; to bar, but I always have some kind of error. In this last case I get:

bar.cpp:48:11: error: prototype for ‘foo& bar::bind(bar::foo&)’ does not match any in class ‘bar’
bar.h:55:12: error: candidates are: gru& bar::bind(gru&)
bar.h:54:13: error:                 bar::foo& bar::bind(bar::foo&)

Plus, I never get any complain about gru. Which, as an additional information, was already there in this program, working perfectly along with bar and main, before I added foo.

Any helpful ideas? Thanks a lot :)


Solution

  • Thank you a lot guys for the answers. In many ways they were helpful.

    In the end I realized that I had to reorder all the #include's in my code, because, as you may have realized, there were a lot more coding and what I put here was a simpler version (sorry for that).

    So, my final solution was to include class bar; in foo.h and class foo; in bar.h. Then reorder the includes in main.cpp and the Makefile.

    Thanks again ;-)