views:

194

answers:

5

Is there a way in C++ to create an anonymous namespace, and only export a single function out of it?

I want something like:

namespace {
  void Bar() {}
  void Foo() { Bar(); }
}

Now, I want to somehow access to Foo() yet make sure there's no way to touch Bar()

Thanks!

A: 

Define Bar as a global static function in the CPP file that contains the function body for Foo.

Edit: Its worth noting that this will only cause a link time error.
Edit2: And I ran a quick test and it seems you can't extern to an anonymous namespace. Edit3:

Something like this would seem sensible (and lose the namespace)

static void Bar()
{
}

void Foo()
{
    Bar();
}

You can now "extern void Foo();" but if you try the same with Bar then the linker will fail as Bar no longer has external linkage.

Goz
This use of static is deprecated in C++ (see 7.3.1.1/2 of either the current Standard or the C++0x draft).
James Hopkin
+2  A: 

You could place them in different header files and make sure clients only get the header file that declares Foo(). However, you cannot implement Foo() inline with that solution.

Space_C0wb0y
+7  A: 

If you want to export the function, you'll have to put it outside the anonymous namespace.

namespace {
  void Bar() {};
};
void Foo() { Bar(); };
Didier Trosset
The anonymous namespace is meant to not leave the cpp (obj) file. So export and anonymous are different sides of the coin.
Totonga
This doesn't restrict access to `Bar()`
quamrana
It does restrict access to Bar() from other compilation units.
Didier Trosset
+1  A: 

why not

namespace {
  void Bar() {};
};
void Foo() { Bar(); };

?

an anonymous namespace is accessible from the file you created it in

f4
+3  A: 

Since you want Foo() to have external linkage, you should declare it in a header file:

#ifndef FOO_H
#define FOO_H

void Foo();

#endif

Now everyone can see and call Foo()

But in Foo.cpp:

#include "Foo.h"

namespace {
    void Bar(){ }
}

void Foo(){ Bar(); }

Now, as long as you control the source file Foo.cpp, no one can change access to Bar()

quamrana
sellibitze