Force forward declarations for C ++ code on Mac (using Xcode)

This is a weird problem that I was wondering if anyone else had seen. We write cross platform C ++ code for Mac and PC, and this only happens on Mac.

Let's say I have a class whose .h file looks like this.

class X {
    int _myValue;
    void myFunction();


And I have another class whose .h file looks like this:

#include "X.h"
class Y {
     X _myObj;


It won't compile. We are getting an error indicating that X is undefined. The solution is to add a forward declaration for X to the Yh file, for example: class X;

We've been doing this for a while, but now we find ourselves in a situation where it doesn't work that well. For example, if we have a .h file that has a template method defined in the .h file, and that method refers to a method in another class, the compiler doesn't know anything about it. Likewise, if we reference an enum that was defined in a class that was included, the compiler does not recognize it (the workaround for this problem was to enumerate in a separate .h file, and it brought it up just fine).

It's almost as if the compiler is not extracting data from the included .h file when compiling the .cpp file.

I'm just wondering if anyone has seen anything like this or had a chance to investigate.

Many thanks...


source to share

3 answers

There is a common system header file X.h

that is part of the X11 window traversal toolkit. I recommend changing the name of your header file so that it doesn't clash with any system headers.

You might try to change your compilers to force it to consider the directory containing your header file before your system includes directories, but this is probably more effort and more fragile.



For your first problem (classes), the correct answer is to use a forward declaration. You should avoid including project files in other files included in the project. This can create include loops (which is most likely your problem if I had to guess). It also creates excessive collection when you change the title.

For your other problems (enums, templates), it usually has to do with loops. Overcoming these cycles while avoiding involves making the best choices whenever possible.

See Best examples of header files for typedefs for more information on this issue and best practices .



I'm just surprised that nobody mentioned the canonical schema for included files like


#ifndef FOO_H
#define FOO_H
// body of the include file


I suspect that in this particular case, the collision of "xh" and "Xh" might be the problem you are seeing, but if you don't protect included files like this, it will eventually bite you.

With this protector, you can include "xh" anywhere.



All Articles