禁用 Clang 中的"cast from pointer to smaller type uint32_t"错误



我正在从事一个学校项目,该项目涉及在实验性硬件上放置大量的C 代码。不幸的是,该硬件为64位,并且代码包含许多指示指示器的指针算术实例,即通常会执行reinterpret_cast<uint32_t>(ptr)

一个一个接一个地浏览它们会非常乏味,而且由于这是一个实验项目,所以我很乐意为"黑客"的解决方法安定下来。因此,相反,我修改了MALLOC的实现,以确保它永远不会将内存分配到4GB限制以上。从技术上讲,这些铸件应该是有效的。

问题是,我该如何向Clang解释这一点?我遇到的错误是:error: cast from pointer to smaller type 'uint32_t' (aka 'unsigned int') loses information。有没有办法禁用它?

谢谢大卫

我从cpplang slack上的某人那里获得此功能,可以用-fms-extensions禁用它:

查看" diagnosticsemakinds.td",它显示为err_bad_reinterpret_cast_small_int,https://github.com/llvm-mirror/clang/clang/blob/blob/release_50/include/clang/clang/clang/basic/diaregnosticsemakinds.td#l61933 " semacast.cpp"中有两次发生 - 其中一项暗示它对MS扩展很敏感,https://github.com/llvm-mirror/clang/blob/blob/blob/release_50/lib/lib/lib/sema/semacast.cpp#l211212 一个人可以尝试-fms-extensions(希望不是-fms-compatibility),但这会带来所有Shebang。

我同意您应该咬住子弹并修复代码以使用正确的整数类型。但是要回答您的问题: no ,您不能禁用它,尽管您可以解决。

许多错误来自警告。一般而言,这是一件好事,但是如果您想禁用警告,那就去做。由于罪魁祸首可能是类似于-Wall的东西,它可以保留许多警告,因此您应该选择性地禁用此警告。错误消息提到了负责错误消息的诊断,例如... [-Wextra-tokens](如果没有,请删除-fno-diagnostics-show-option标志)。然后,您可以通过添加-Wno-extra-tokens完全禁用此诊断(同样,"额外的令牌"警告是一个示例),或者通过-Wno-error=extra-tokens

但是,此特定错误不是由于警告,我找不到任何禁用错误的选择(因为大多数错误是致命的)。

,但仅截断整数值,而不必修复uint32_t 的所有错误用途,但您可以使用static_cast<uint32_t>(reinterpret_cast<uintptr_t>(ptr))。不用说,这仍然是错误的。

如何使用uintptr_t,大多数指针算术仍然可以工作。

将此代码保存为mycast.hpp,然后将-include mycast.hpp添加到您的Makefile

#include <cstdint>
template<typename U, typename T>
U Reinterpret_cast(T *x) {
    return (U)(uintptr_t)x;
}
template<typename U, typename T>
U Reinterpret_cast(T &x) {
    return *(U*)&x;
}
#define reinterpret_cast Reinterpret_cast

除非您的代码太棘手,否则他们应该尽力而为。

您的策略对堆栈分配的对象不起作用,请小心!!您可以在必要时将一些调试/记录逻辑插入Reinterpret_cast

我在没有C 11的项目中遇到了同样的问题,并这样围绕着它:

inline int PtrToInt(void* ptr)
{
    void* clang[1];
    clang[0] = ptr;
    return *(int*)clang;
}

相关内容

最新更新