Jesse Emond
Jesse Emond

Reputation: 7490

Compiling Error with C++ and namespace

Here's the whole code getting the errors:

Engine.h

#ifndef ENGINE_H
#define ENGINE_H

#include "DXManager.h"

namespace XEngine
{
    class Engine
    {
    };
}

#endif

DXManager.h

#ifndef DX_MANAGER_H
#define DX_MANAGER_H



namespace XEngine
{
    class Engine; // forward declaration

    class DXManager
    {
    public:
        void run(Engine *engine);
    };
}

#endif

DXManager.cpp

#include <iostream>

#include "Engine.h"
#include "DXManager.h"

using namespace XEngine;

void DXManager::run(Engine *engine)
{
    std::cout<<"DXManager::run"<<std::endl;
}

With these 30 lines of code, I'm getting 20 errors like:

'XEngine' : a namespace with this name does not exist
'XEngine' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
syntax error : identifier 'Engine'

Clearly, I'm missing something important here. What am I doing wrong?

note: I am aware that circular dependency is a bad thing, but in my particular case I believe that it is relevant.

Upvotes: 3

Views: 3566

Answers (3)

Serge Dundich
Serge Dundich

Reputation: 4429

In DXManager.cpp you are not just using some names from namespace XEngine. You define the function in that namespace.

So must be:

DXManager.cpp

#include <iostream>

#include "Engine.h"
#include "DXManager.h"

namespace XEngine {

void DXManager::run(Engine *engine)
{
    std::cout<<"DXManager::run"<<std::endl;
}

}

AFAIK some of the compilers (like MSVC) process using variant too. But it is not correct because your syntax tries to define function ::DXManager::run - not ::XEngine::DXManager::run you intend to define.

Upvotes: 3

Javier
Javier

Reputation: 4623

When Engine.h includes DXManager.h, the latter defines a class XEngine::Engine without declaring the namespace first.

Upvotes: 1

Khaled Nassar
Khaled Nassar

Reputation: 884

In the forward-declaration of class Engine the namespace XEngine doesn't exist at this point.

A workaround would be moving the declaration inside the namespace block.

Upvotes: 2

Related Questions