c++ - MSVC 中的不透明指针会生成编译器错误

标签 c++ c visual-c++ compiler-errors opaque-pointers

main.c

#include "stackg.h"

int main()
{
    return 0;
}

stackg.h

#ifndef STACKG_H
#define STACKG_H

#ifdef __cplusplus
extern "C" {
#endif

typedef struct stack_gt* stack_gt;

stack_gt stkg_init(
                  void* (*alloc)(const void* data, const int size),
                  void (*dealloc)(void* data),
                  void (*copy)(void* data_d, const void* data_s),
                  const int size
                  );
void stkg_free(stack_gt s);
int stkg_is_empty(stack_gt s);
int stkg_is_full(stack_gt s);
const int stkg_size(const stack_gt s);
void stkg_clear(stack_gt s);
int stkg_push(stack_gt s, const void* data);
int stkg_pop(stack_gt s, void* data);
int stkg_peek(stack_gt s, void* data);

#ifdef __cplusplus
}
#endif

#endif

上述程序使用GCC编译器编译成功,但在MSVC2008中出现以下错误:

error C2040: 'stack_gt *' differs in levels of indirection from 'stack_gt'

我应该告诉 MSVC 怎样让它编译程序而不更改代码中的任何内容?

编辑

stackg.h 第 8 行发生错误:: typedef struct stack_gt* stack_gt;

编辑2

如果没有别的事,我会选择typedef struct _stack_gt* stack_gt;

最佳答案

问题在于:

typedef struct stack_gt* stack_gt;

你给了stack_gt一个不同的类型,而这工作正常:

typedef struct stack_gt* stack_gtB;

clang 为我们提供了更好的错误消息:

error: typedef redefinition with different types ('struct stack_gt *' vs 'stack_gt')

这在 C++ 标准草案 7.1.3 部分中有介绍 typedef 说明符段落6:

In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type. [ Example:

class complex { / ... / };
typedef int complex; // error: redefinition

—end example ]

使用相同的名称也可以,所以这样就可以了:

   typedef struct stack_gt stack_gt;

第 3 段涵盖:

In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers. [ Example:

typedef struct s { / ... / } s;
typedef int I; 
typedef int I;
typedef I I;

—end example ]

关于c++ - MSVC 中的不透明指针会生成编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739408/

相关文章:

c++ - 隐式转换不起作用

c - 在自定义 malloc 中附加调试 header

可变参数函数中的冲突类型

c++ - CLI/C++ 究竟是什么?它与 'normal' c++ 有何不同?

c++ - 默认构造函数是否总是初始化所有成员?

c++ - clang 10 C++ 20概念如何为类方法指定复合要求?

c++ - 哪个库用于体素数据结构?

C - 链表不兼容的指针类型

c++ - C++11 是否允许(不需要)释放/获取 volatile 关键字的语义

c++ - 处理重新定义 int 类型(uint16_t、int16_t 等)的代码并且 Boost 不喜欢它