c++ namespace export - c++

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!

If you want to export the function, you'll have to put it outside the anonymous namespace.
namespace {
void Bar() {};
};
void Foo() { Bar(); };

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()

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.

why not
namespace {
void Bar() {};
};
void Foo() { Bar(); };
?
an anonymous namespace is accessible from the file you created it in

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.

Related

When is a namespace::function() declaration useful?

Single File Example
Here is a simple program using namespaces.
#include <iostream>
namespace foo {
void hello();
}
void foo::hello() {
std::cout << "hello\n";
}
void foo::hello(); // Why is this syntax allowed? When is it useful?
int main() {
foo::hello();
}
This program compiles fine and produces the expected output.
$ ./a.out
hello
I want to know when is the void foo::hello(); declaration useful? In this program, clearly this declaration is redundant. But since this syntax exists, this must be useful in some other scenario?
Two-File Example
Here is an example that shows that the void foo::hello(); declaration standing alone is useless.
// foo.cpp
#include <iostream>
namespace foo {
void hello();
}
void foo::hello() {
std::cout << "foo::hello\n";
}
// main.cpp
void foo::hello(); // This does not work!
int main()
{
foo::hello();
}
Trying to compile the above two files leads to the following errors:
$ clang++ foo.cpp main.cpp
main.cpp:1:6: error: use of undeclared identifier 'foo'
void foo::hello();
^
main.cpp:5:5: error: use of undeclared identifier 'foo'
foo::hello();
^
2 errors generated.
The only way to fix main.cpp in the above example seems to be include the namespace declaration:
// main.cpp - fixed
namespace foo {
void hello();
}
void foo::hello(); // But now this is redundant again!
int main()
{
foo::hello();
}
So after we get this code to compile properly, the void foo::hello(); declaration seems redundant again. Is there any scenario where such a declaration would be playing a useful role?
In most cases in C++, for anything that can be either declared without defining it or can be completely defined, a declaration or a definition of that thing can appear in all the same contexts. So this is probably just a way of keeping the pattern consistent.
The C++ Standard does not go out of its way to forbid things that are a logical consequence of its other rules but just not useful, as long as it's reasonably clear what will happen if someone does it anyway. If it did add these restrictions, that would put extra work on compiler writers for no real benefit.
From [basic.def]/1
A declaration may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. If so, the declaration specifies the interpretation and attributes of these names.
Which allows code like this
#include <iostream>
void foo();
void foo();
void foo();
void foo();
void foo();
int main()
{
foo();
}
void foo() { std::cout << "foo()"; }
To be valid. There is no harm in having multiple declarations of a function, as long as we have only one definition, it won't cause an issue.
Another example would be you have a global function you want to be a friend of multiple classes. You would include that function prototype in each class header so you can friend it and then you would include all of those class headers in your main source file. So
A.h
void foo();
struct A { friend void foo(); }
B.h
void foo();
struct B { friend void foo(); }
main.cpp
#include "A.h"
#include "B.h"
...
and that would be converted to
main.cpp
void foo();
struct A { friend void foo(); }
void foo();
struct B { friend void foo(); }
...
So we would want this to be legal.

Forward declaring a function in a namespace inside another function in that namespace

I have two source files, a.cpp and b.cpp. In a.cpp, I have a function, foo:
namespace ns { void foo() { std::cout << "foo!"; } }
In b.cpp, I have another function in namespace ns in which I'd like to prototype and call foo:
namespace ns
{
void bar()
{
void foo();
foo();
}
}
While the above is syntactically valid, it leads the compiler to think that foo is in the global namespace (or at least that's what I've deduced from the linker errors I get when I do this). My first two ideas to fix that were void ns::foo(); and namespace ns { void foo(); }, but neither is valid. Is it possible to correctly prototype this function inside bar?
Note that I know I could simply move this to the file scope or a header file, there have been many questions asked about this, but I want to specifically prototype it inside another function. My compiler is MSVC 14.0 with the latest update.
EDIT: Based on some tests I've done and our discussion in the comments, I believe this is an MSVC bug. Compare:
namespace ns
{
void bar()
{
void foo(); // link error, MSVC assumes global namespace
foo();
}
void foo() { }
} // namespace ns
This fails, as stated previously. However, moving the prototype out of the function makes MSVC correctly place the prototyped function in the enclosing namespace:
namespace ns
{
void foo(); // all fine
void bar()
{
foo();
}
void foo() { }
} // namespace ns
The standard is clear about this point:
3.3.2/11: (..) Function declarations at block scope and variable declarations with the extern specifier at block scope refer to
declarations that are members of an enclosing namespace (...)
Consequently:
void bar()
{
void foo(); // should refer to ns::foo() according to 3.3.2/11
foo();
}
and the linking should refer to the separately compiled function which has the same signature:
1.3.17 signature: <function> name, parameter type list , and enclosing namespace (if any) [Note: Signatures are used as a basis for
name mangling and linking.—end note ]

Strange output with static objects

I can't understand what's happening...
Suppose that I have the following code:
// main.cpp
#include "some_header.h"
void bar();
int main()
{
foo();
bar();
}
// file.cpp
#include "some_header.h"
void bar()
{
foo();
}
// some_header.h
#include "foo.h"
inline
void foo()
{
static Foo instance;
}
// foo.h
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo() \n"; }
~Foo() { std::cout << "Foo::~Foo() \n"; }
};
Output
Foo::Foo()
Foo::~Foo()
The question is: why there's no second "Foo::Foo()" in the output? I think that it should be here because each translation unit (in my case main.cpp and file.cpp) should have its own Foo object (because of static keyword). Am I wrong? Can somebody quote the standard, please?
If i move the definition of Foo object from the function like this
// some_header.h
#include "foo.h"
static Foo instance;
inline
void foo()
{
}
the output will be
Foo::Foo()
Foo::Foo()
Foo::~Foo()
Foo::~Foo()
Is it inline magic or am I missing smth more fundamental?
What I need to do - I need to add boost::mutex object in some function for my header-only library to synchronize some WinAPI function calls like this:
inline
void some_func()
{
static boost::mutex sync;
boost::lock_guard<boost::mutex> lock(sync);
// Call some WinAPI function
}
How can I do it?
MSVC-11.0.
static is a heavily overloaded keyword in C++. At namespace scope, it means "entity has internal linkage, so every translation unit will have its own copy." At function scope, it means "there is only one such entity for the function and it persists across function calls."
So in your case, the funcion foo() simply has one object Foo instance with local scope, but global lifetime.
As for your mutex question, I can't see anything wrong with doing just what you posted in the question. some_func() will have a single instance of the mutex, and all calls to some_fucn() will share that one instance (and since C++11, it will be correctly and thread-safely initialised by the first such call). I'd say that's exactly what you need.

Defining a function once that appears in multiple name spaces

I am trying to define a common interface to a set of functions and classes that will have multiple different backend implementations (Using different libraries).
As such I'd really rather, simply, define a function in one place and not in each separate namespace.
For example, I have a global function:
extern void Func();
Now I want to have 3 separate implementations of that function. One would be a straight C, One would be a hand coded assembler and one would be using library 'x'.
I am effectively trying to avoid doing the following:
namespace C
{
extern void Func();
}
namespace Asm
{
extern void Func();
}
namespace LibX
{
extern void Func();
}
Is there a good pattern to avoid doing this? When there are 100 odd functions it will become much more of a pain.
The only idea I can think of is to move all the definitions into a header file that has no header guards and then doing:
namespace C
{
#include "Functions.h"
}
namespace Asm
{
#include "Functions.h"
}
namespace LibX
{
#include "Functions.h"
}
Is there a better way of doing this that anyone can think of?
Make it a virtual function in an abstract base class. Implement it whenever you feel like it in a derived class.
class Foo{
public:
virtual void bar() const=0;
}
class FooASM:public Foo{
public:
virtual void bar() const{ ... }
}
etc.
I guess you want static polymorphism - means a template or a macro:
Template:
#include "C_Functions.h"
#include "Asm_Functions.h"
#include "LibX_Functions.h"
enum Namespace
{
NamespaceC,
NamespaceAsm,
NamespaceLibX
}
template <Namespace> Func();
template <> inline Func<NamespaceC>() { return C_Func(); }
template <> inline Func<NamespaceAsm>() { return Asm_Func(); }
template <> inline Func<NamespaceLibX>() { return LibX_Func(); }
const Namespace NSpace = ...
inline void f() {
Func<NSpace>()
}
An advantage is: You may have a common implementation for a specific function.
Similar you may do with macros (or you combine it)
I fear it ends up in #ifdef ... anyway, unless you try to have one lib for any hardware/system (which is pointless, in my view).

creating methods that doesn't depend on a object

How can I create bunch of methods that doesn't depend on any object ( in my file there is no classes , no objects , no main , nothing but the methods) all in one cpp/hpp file and how to declare them ?
Create a namespace. Something like this:
Utils.h
namespace Utils
{
void myMethod();
}
Utils.cpp
namespace Utils
{
void myMethod()
{
//Implementation
}
}
If you want them to be public, i.e. available in multiple translation units, the best way is to include them in a namespace, declare them in the header and implement them in a single implementation file:
//functions.h
namespace MyFunctions
{
void foo();
void goo();
}
//functions.cpp
namespace MyFunctions
{
void foo() {}
void goo() {}
}
IMPORTANT
If you provide the definition in the header, you should mark them inline, otherwise including that header in multiple translation units might result in a linker error:
//functions.h
inline void foo() {
//..
}
inline void goo() {
//..
}
If you only want them available in a translation unit, define them in that implementation file in an anonymous namespace (or declare them static):
//fileThatUsesFunctions.cpp
namespace
{
void foo() {}
void goo() {}
}
You declare them the same way you would in C. It can be within a namespace or outside of a namespace. There is no difference other than the fact that they are not in a class.
If you want to use the functions in C later you should prepend them with extern "C".
extern "C" void foo();
Nothing stops you from writing free functions. If you think that a function should be global then free functions are quite appropriate.
You should place them in a namespace. Naveen's example is spot on.
As an additional note, if you wish to hide certain functions or data units within the namespace (thereby mimicking 'private' access), place those functions and data units in an anonymous namespace, nested within the parent namespace. For example:
namespace Foo
{
publicFunction1();
publicFunction2();
namespace
{
privateFunction1();
std::vector<Bar> privateData;
}
}
Items within a nested, anonymous namespace are only accessible to the items within the parent namespace. I've found this to be singularly useful.
To define a function that doesn't depend on an object simply declare them directly.
// MyFile.h
int some_function();
// MyFile.cpp
int some_function() {
return 42;
}
Using C++ though it would be a good idea to declare them in a namespace though. This doesn't give them a dependcy on an object but does reduce global namespace pollution
// MyFile.h
namespace MyNamespace {
int some_function();
}
// MyFile.cpp
using MyNamespace;
int some_function() {
return 42;
}