unnamed namespaces

Started by
12 comments, last by TonyFish 20 years, 2 months ago
The problem with unnamed namespaces is that the unique identifier for the namespace is different in each translation unit. This means it is practically impossible to split the implementation of the classes declared in the unnamed namespace across multiple translation unit, and will no doubt give you linker errors. e.g.

//unnamed.hpp...namespace{class A{ public: void somefunc();};}...//A.cpp#include "unnamed.hpp"void someuniqueidentifier::A::somefunc(){...}//Facade.cpp#include "unnamed.hpp"#include "Facade.hpp"void Facade::somefunc(){anotheruniqueidentifier::A instance;instance.somefunc();}


Since the unique identifier is different in each translation unit, you have ended up defining a class that belongs to a different namespace than you have used, and so you will get a linker error .

Only way you could solve this is by defining the unnamed namespace objects inside the unnamed namespace.


[edited by - Jingo on February 21, 2004 6:49:12 AM]
Advertisement
Well I've solved it thus:

*all the relevant external headers*namespace Compiler{    class Facade;    namespace // _UNIQUE_    {        #define _HEADER_            #include "SubAlpha.hpp"            #include "SubBeta.hpp"        #undef	_HEADER_        #define _SOURCE_            #include "SubAlpha.hpp"            #include "SubBeta.hpp"        #undef	_SOURCE_    }    class Facade {…};}


Where SubAlpha.hpp will look like this

#ifdef _HEADER_class SubAlpha{    friend class Facade;    friend class SubBeta;public:    int Method(void);private:    SubAlpha();};#endif#ifdef _SOURCE_int SubAlpha::Method(void) {…}#endif


This works but if it is used to hide 99% of a large project results in a massive translation unit which will a. be slower to compile and more importantly b. require a re-compile of everything whenever anything is changed.

Of course if anyone can think of anything wrong with this or any way of improving it I'd love to hear.

Thanks

[edited by - TonyFish on February 21, 2004 5:42:27 PM]
<Fish>{
Since he uses pointers, objects aren''t actually created, so what he did wouldn''t cause an infinite loop of inclusions.
And the rockets' red glare, the bombs bursting in air,gave proof through the fight that our flag was still there.Oh say, does that star-spangled banner yet waveover the land of the free and the home of the brave?
Christ could people stop posting about the pointers and possible cyclic dependencies. It was just something to fill the skeleton example. Jeez
<Fish>{

This topic is closed to new replies.

Advertisement