避免警告 8 位 Ada 布尔返回类型,使用 Char

问题描述 投票:0回答:1

我一直致力于清理迂腐代码的警告,我们将警告视为错误。我有 Ada 和 C++ 之间的接口代码,看起来像这样:

Ada manager.ads:

function Foo(ID_Type : in Integer) return Boolean;
pragma Import(CPP, Foo, "Foo");

C++ Adamanager.cpp:

extern "C" bool Foo(int32_t ID)
{
  return Manager::GetManager()->Bar(ID);
}

C++ Adamanager.h:

extern "C" bool Foo(int32_t ID);

C++ 管理器.cpp:

bool Manager::Bar(int32_t ID)
{
   //function body
   return answer;
}

C++ 管理器.h

static bool Bar(int32_t ID);

gcc -c manager.ads 的输出:

warning: return type of "Foo" is an 8-bit Ada Boolean
warning: use appropriate corresponding type in C (e.g. char)

我有很多这样的案例。

为了消除警告,我是否需要将所有布尔值替换为 char 或其他一些 8 位类型,然后在 Ada 主体代码中进行显式类型转换?为什么编译器会选择布尔值是 8 位的?

c++ ada extern pragma
1个回答
2
投票

这种方法有很多问题。首先,您的 C 函数应该使用 C 类型声明。虽然有声明

bool
int32_t
的标准标头,但由于您不包含它们,您应该将它们替换为相应的 C 类型,可能是
char
int

extern "C" char Foo (int ID);

其次,由于您的函数被声明为 C 而不是 C++,因此您应该使用约定 C 而不是 CPP 来导入它。 (在 C++ 周围声明此类 C 包装器的全部原因是为了避免直接与 C++ 接口的问题。)

第三,使用非约定 C 类型(如 Integer 和 Boolean)与 C 接口是一个坏主意。它可能有效,但不能保证继续使用未来版本的编译器。最好使用 Interfaces.C 中的适当类型

第四,你不能保证返回的值会被限制为0或1,所以你需要像C一样对待它,0或非0。

有了这一切,你的 Ada 就变成了

with Interfaces.C;

function Foo (ID : in Integer) return Boolean is
   function Foo (ID : in Interfaces.C.int) return Interfaces.C.unsigned_char
   with Import, Convention => C, External_Name => "Foo";

   use type Interfaces.C.unsigned_char;
begin -- Foo
   return Foo (Interfaces.C.int (ID) ) /= 0;
end Foo;

尽管您可能想在 Ada 端使用 Integer 以外的类型作为 ID。

这应该可以正常工作,消除您的警告,并提供一些针对编译器更改的保护。

© www.soinside.com 2019 - 2024. All rights reserved.