views:

40

answers:

2

Hi.
I have two source files, one named main.cpp (where the namespace M is defined) and the file engines.h (where serveral names are defined).
main.cpp includes engines.h.
engines.h need to use the stuff inside M, and M needs to use the stuff inside engines.h.

I get an error doing using namespace M; in engines.h.

+3  A: 

Don't use using namespace inside header files. This will get all the symbols from the namespace inside each translation unit that includes that header file, so you'll have a symbol mess (name conflict, which is probably what you're facing in your situation). Use full qualification inside the header files, or at least use the using namespace statement locally (inside a function or method where you what to improve readability).

For your situation, what is the error you get? What is the content of the headers?

Cătălin Pitiș
engines.h contains types(classes basing on a base type defined in main.cpp). There are a few namespaces to group the types(Player Engines, Map Engines, Block Engines, Trigger Engines, and the sub-ordered namespaces to group the features called F. I have to put that into a seperate file, becouse main.cpp will be compiled(so that you are not able to change anything), and you can define your own engines. in main.cpp there's all the managment code and (almost) everything else, like networking and such >.>
aPoC
@aPoC, you should define that class in `main.h`, so that you can include that class in `engines.h`. Class definitions and names need to be known by inclusion to be used in C++.
Johannes Schaub - litb
+2  A: 

You cannot do using namespace M before the namespace was defined. If there is a cyclic dependency, you need to solve it by using one or more techniques

  • Forward declare if your uses don't need to know the members or size of classes, but just handle with pointers or references to them:

    namespace M { class MyCow; }
    
  • Define stuff in engines.cc

    // engines.h
    void f();
    
    
    // engines.cpp
    #include "main.h"
    void f() { MyCow muuh; }
    
  • Use of the pimpl idiom reduces dependencies even more, as it keeps headers free of headers that are only used by implementations..

Split the part in .h files for the interface and .cpp files for the implementation to handle such dependencies. That way, headers are less dependent on other headers, and implementation files can include the headers.

Johannes Schaub - litb