gpt4 book ai didi

c++ - 我应该在命名空间中包含头文件吗?

转载 作者:可可西里 更新时间:2023-11-01 18:04:08 29 4
gpt4 key购买 nike

目前我正在开发一个 c 框架,我想在其中嵌入一个 c++ 包。但是,会发生很多命名冲突。所以我决定向 C++ 源代码添加一个命名空间。现在的问题是我应该在 namespace { } block 中移动 #include "header.h"吗?我只是花了一些时间找出由以下代码导致的错误。

原始 C++ 源代码

在啊啊

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

在.cpp中

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

然后我像这样添加了命名空间

新啊.h

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() 尚未声明。

之所以将#include 指令放在命名空间 block 中,是因为我导入的c++ 包也使用#ifndef 标志来包含头文件,如下所示。所以我认为简单的方法是将所有代码放在命名空间 block 中{}

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

现在我通过在cpp 文件中添加额外的行解决了这个问题

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

但是我对这个解决方案不满意,因为 unistd.h header 已经包含在 a.h 中,但是在命名空间 MyAddedNameSpace 中,或者我应该将前缀 MyNameSpace 添加到编译器提示没有声明此类函数的所有函数调用中吗?

感谢回复。

最佳答案

你不应该放置 #include您自己的命名空间内的指令。你所做的是放置所有unistd.h的内容。也在你的命名空间内;因此曾经是(并且应该保留!)::close()现在声明为 MyAddedNameSpace::close() .这不是您想要的。

添加行的“解决方案” #include <unistd.h>在你的 .cpp 文件的顶部解决了这个问题,但只针对这个 .cpp 文件。你所做的是以正确的方式包含库头(没有你的命名空间),然后当你的头(a.h)被包含时,它会执行 #include <unistd.h>再次(这次 在你的命名空间内),但这次文件中的 include guards 阻止它被再次处理。所以对于 this .cpp 文件你没问题,但任何其他文件都可以 #include <a.h>将遇到与您最初遇到的问题相同的问题。

在极少数情况下,您可能有充分的理由使用 #include在您自己的命名空间中,但您很可能会包含您自己的 header 之一(或其他文件) - 而不是库 header ! - 即便如此,它也可能不是理想的解决方案。

在啊啊

#include <unistd.h>

namespace MyAddedNameSpace {

struct File
{
void func(int fd);
};

}

在.cpp中

#include "a.h"

namespace MyAddedNameSpace {

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

}

关于c++ - 我应该在命名空间中包含头文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764481/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com