C++: How to force libc declarations into std::?

不想你离开。 提交于 2019-12-05 11:07:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!