0

I'm trying to help a coworker get something compiled - essentially, he was trying to reduce dependencies for a small executable we need to make from a larger software system.

I'm not sure I can fully explain the problem as I don't completely understand it... but I'm going to show what's going on here:

Library A:  File: A.h

namespace CF {
    typedef sometype B;
};

Library C:   File C.h

//Forward declare Class
class CF::B;

Class D {
    public:
        B* UseB();
};

Library C:   File C.cpp

#include "C.h"
#include "A.h"
using CF::B;

B* D::UseB()
{
    return new B;
}

Sorry, I know this looks a little crazy but I have tried to simplify it from the set of files that we're actually dealing with.

We're typically getting either a multiple definition error on CF::B, or when we play with the code and change it around, sometimes in the CPP file it just doesn't recognize the type of CF::B.

I guess my first question is... can I forward declare the typedef like we've tried, or is there some other way to deal with the fact that B is a typedef in CF namespace, and we don't want it to be directly included in the C.h file?

John Humphreys
  • 37,047
  • 37
  • 155
  • 255

2 Answers2

2

This will probably help you:

a.h:

#ifndef NAMESPACE_A
#define NAMESPACE_A

namespace A
{
    class B
    {
        public: int i;
    };
}
#endif

c.h:

#ifndef NAMESPACE_A
#define NAMESPACE_A
namespace A
{
    class B;
}
#endif

class D
{
    public:
        A::B* UseB();
};

main.cpp:

#include "a.h"
#include "c.h"
using A::B;

B* D::UseB()
{
    return new B();
}

int main(int argc, char* argv[])
{
    D* d = new D();
    B* b = d->UseB();
    b->i = 1;
    return 0;
}

... works fine for me ;)

LihO
  • 41,190
  • 11
  • 99
  • 167
1

A forward declaration would be more like

namespace CF { class B; }

The compiler cannot make anything out of CF::B unless it already knows CF to be a namespace.

You also cannot forward declare a typedef, because the compiler must know if B is a class or a built in type. Some built in types have special rules, like char* or void*.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • This wasn't a complete solution, but it's advanced the build a little farther so we're making more progress - so I think it was definitely the best I'll get given the sloppy question :) thank you very much for the help! +1. – John Humphreys Jan 25 '12 at 19:54