aPoC
aPoC

Reputation: 7983

visibility problems with namespaces

I have two source files, one named main.cpp (where the namespace M is defined) and the file engines.h (where several 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.

Upvotes: 1

Views: 126

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507313

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.

Upvotes: 2

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14317

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?

Upvotes: 3

Related Questions