自动检测函数参数是否需要加"const"限定符

Automatically detect if need to add a "const" qualifier in function parameters

我编写了一个 PMPI 分析库,它拦截了许多 MPI 函数。 在我的本地机器上,我安装了 OpenMPI,一些函数参数有一个 const 限定符,例如:

int PMPI_Gather(const void *sendbuf, int sendcount, ...)  

所以很自然地,我的 PMPI 库在相应的钩子函数中也有那些 const 限定符。但是,我经常 运行 东西的远程机器有一个 MPI 安装,其中 mpi.h 中的函数参数没有 const 限定符,所以当我编译我的库时,我会收到一大堆警告函数声明不兼容。当然,我可以忽略警告、抑制它们或手动删除 const 限定符。

我想知道是否有更优雅的方式来处理这种情况,是否有可能以某种方式检测 mpi.h 中的函数声明是否具有 const 参数并自动添加或删除 const 限定符编译期间的分析库代码,或者它可能是某种配置功能。

通常在可以在多个地方定义一个变量或定义的情况下使用#ifdef#ifndef。 你会有这样的东西:

#ifndef _YOU_CONSTANT #define _YOU_CONSTANT #endif

MPI 3.0 中添加了

const-C 绑定的正确性,即 IN 参数的 const 指针。您可以按以下方式处理:

#if MPI_VERSION >= 3
    #define MPI_CONST const
#else
    #define MPI_CONST
#endif

int PMPI_Gather(MPI_CONST void *sendbuf, int sendcount, ...)

注意:您可以在 "diff to 3.0" version of the standard.

A.2 C 绑定 部分轻松看到更改

#ifdef ... 的替代方法是简单地检查函数获得的类型:

typedef int PMPI_Gather_noconst (void *sendbuf, int sendcount, ...);
typedef int PMPI_Gather_const (const void *sendbuf, int sendcount, ...);

if( _Generic(PMPI_Gather, PMPI_Gather_noconst*:true, PMPI_Gather_const*:false) )
{
  PMPI_Gather_noconst* stuff;
  ...
}
else
{
  PMPI_Gather_const* stuff;
  ...
}