gpt4 book ai didi

c++ - C++ 命名空间在 Windows 和 linux 中的行为是否不同?

转载 作者:行者123 更新时间:2023-12-04 17:05:23 25 4
gpt4 key购买 nike

所以我在这个 dll 中使用了两个 typedef,它们被包裹在一个命名空间中,就像这样,
常量.h

namespace constants
{
typedef int Integer;
typedef float Decimal;
}
现在我在 dll 中使用它的地方,我使用了命名空间而不使用像 using namespace constants 这样的完全限定名称。 .
现在有一个文件 handler.h 正在导入另一个实用程序.h,而后者又在导入这个常量 .h
实用程序.h (与constants.h 相同的dll)
#include "constants.h"
using namespace constants;
handler.h(另一个dll)
#include "utility.h"
#include "common.h"
此处的 common.h 具有为另一种数据类型定义的相同 Integer 和 Decimal typedef。
据我所知,我们什么时候使用 using namespace constants typedefs 范围将仅在该翻译单元内,即这里的utility.h。
因此,在 common.h 中定义的 typedef 不会与 Utility.h 中存在的常量 typedef 混淆,因为它们被包装在命名空间下。
common.h (第三个dll)
typedef unsigned long int Integer
这在 Visual Studio 中运行良好,并且二进制文件已成功构建。
但是在 Linux 上我得到了
 error: reference to 'Integer' is ambiguous
为什么相同的代码在 Linux 中出现编译器错误,但在 Windows 中没有。
我使用的是 Microsoft Visual Studio 2017,
注意:我知道我们应该始终使用具有完全限定符名称的命名空间。但我只想知道为什么在 win/unix 中的行为不同。

最佳答案

As far as I know when we use using namespace constants the typedefs scope will only be inside that translational unit, i.e here utility.h.


Utility.h 本身并不是一个“翻译单元”。如果将utility.h 包含到另一个文件中,则该其他文件(及其所有包含的文件)是一个翻译单元。
例如,在预处理器处理完包含指令后,handler.h 的内容(在其翻译单元内)将是:
namespace constants
{
typedef int Integer;
typedef float Decimal;
}
using namespace constants;
typedef unsigned long int Integer
这可能是一个问题,因为不合格的类型名称 Integer会模棱两可。

Why the same code is giving compiler error in Linux


您实际上还没有展示您如何使用 Integer ,所以我们无法确认。但是如果编译器是正确的,那么你指的是 Integer模棱两可,这使得程序格式错误。

But the same thing is working fine on visual studio


如果上述关于使用 Integer 的假设是正确的,如果您的编译器没有发出诊断消息,则编译器不符合 C++ 标准。

关于c++ - C++ 命名空间在 Windows 和 linux 中的行为是否不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67630935/

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