我应该在命名空间中包含头文件吗? [英] Should I include header file within a namespace?

查看:815
本文介绍了我应该在命名空间中包含头文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在开发一个c框架,我想嵌入一个c ++包。但是,有很多命名冲突发生。所以我决定添加一个命名空间到C ++源代码。现在的问题是我应该在名称空间{}块中移动#includeheader.h吗?

Currently I am working on a c framework and I want to embed a c++ package into it. However, there are lots of naming conflicts occurs. So I decided to to add a namespace to the C++ source. Now the question is should I move the #include "header.h" within namespace { } block? I just spent some time to figure out a bug which was resulted from the following codes.

原始C ++源

在啊

#include <unistd.h>
struct File 
{
     void func(int fd);
}; 

在a.cpp

#include "a.h"
void File::func(int fd)
{
    ::close( fd );
}

我添加了这样的命名空间

And I added the namespace like this

新的ah

namespace MyAddedNameSpace 
{ 
    #include <unistd.h>
    struct File 
    {
        void func(int fd);
    }; 
}

新a.cpp

#include "a.h"
namespace MyAddedNameSpace 
{
    void File::func(int fd)
    {
        ::close( fd );
    }
}

并且编译器抱怨:: close已被宣布。

And compiler complains that ::close() has not been declared.

为什么我把#include指令放在命名空间块中的原因是因为我导入的c ++包也使用#ifndef标志包括头文件如下。所以我认为简单的方法是将所有代码放在命名空间块{}中

The reason Why I put the #include directive inside namespace block is because the c++ package I imported also use #ifndef flag to include header files as follows. So I think the easy way is to put all codes within namespace block {}

#ifndef 
    #include <header1.h> 
    #include <header2.h>
    ...
#else 
    #include <header3.h>
    #include <header4.h>
    ...
#endif



现在我解决了这个问题, cpp文件中的额外行

Now I solved this problem by adding the extra line in cpp file

#include <unistd.h>  //new added line 
#include "a.h"
namespace MyNameSpace 
{
    void File::func(int fd)
    {
        ::close( fd );
    }
}

但我对unistd以来的解决方案不满意。 h头已经包含在啊,但是在命名空间MyAddedNameSpace内,或者我应该添加前缀MyNameSpace到所有的函数调用,编译器抱怨没有这样的函数声明?

But I am not satisfied with this solution since unistd.h header has already been included in a.h, but inside the namespace MyAddedNameSpace, or should I added the prefix MyNameSpace to all the function calls where the compiler complain no such function declared ?

感谢您的回覆。

推荐答案

.cpp 文件中使用命名空间放置指令
像这样:

Usually it is enough to place the directive using namespace in the .cpp file. Like that:

using namespace MyAddedNameSpace;

    void File::func(int fd)
    {
        close( fd );
    }

希望它有帮助..

这篇关于我应该在命名空间中包含头文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆