So, I find myself in the need of libc in my C++ program. However, I do not like the idea of sprinkling it all over the global namespace. Ideally, I'd like to force the entirety of libc into the std::
namespace so I'd have to do std::memcpy
rather than memcpy
.
Is this possible? And how? I'm willing to use compiler-specific macros if needed (I target only MS VC++ 10.0 and GCC 4.6).
Edit: I do literally mean 'force the declarations into std' - so that they are uncallable without the std:: prefix. Also, I am including cstdio
, not stdio.h
.
Thanks!
You cannot do this, unless it's already done.
The namespace std
is reserved to the Standard Library, it is forbidden to add new members to this namespace. Therefore, if the C-headers are not already embedded within std
, then you have no choice but to accept it.
On the other hand, you can perfectly create a new namespace, cstd
, and bring the symbols from the global namespace in it with using
directives... but it won't make them disappear from the global namespace.
I do literally mean 'force the declarations into std' - so that they are uncallable without the std:: prefix.
You can't do this if your implementation exposes the names in the global namespace. You can use the <cXXX> headers and then use std:: yourself.
This is, perhaps, unfortunate, but it is a consequence of C compatibility, since C does not understand namespaces. C++ has traditionally maintained many kludges and sacrifices for C compatibility.
Make wrapper includes
//stdlib.hpp
namespace std
{
#include <stdlib.h> //edit: changed from cstdlib to stdlib.h
}
If the linker hates this try just declaring the functions you want:
namespace std{ extern "C" {
int memcpy( void *out, const void *in);
} }
The reason some (most?) C++ compilers have the C functions in the global namespace, is simply that they have to use the existing operating system functions. For example, the file functions might not be a separate C library, but the file handling of the OS.
来源:https://stackoverflow.com/questions/4909420/c-how-to-force-libc-declarations-into-std