不透明的C结构:应如何声明? [英] Opaque C structs: how should they be declared?

查看:135
本文介绍了不透明的C结构:应如何声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过两个下列两种风格用C API的声明不透明类型。是否有任何明显的优势,使用一种风格比其他?

选项1

  // foo.h中
typedef结构美孚* fooRef;
无效doStuff(fooRef F);// foo.c的
结构foo的{
    INT X;
    诠释Ÿ;
};

选项2

  // foo.h中
typedef结构_foo富;
无效doStuff(富* F);// foo.c的
结构_foo {
    INT X;
    诠释Ÿ;
};


解决方案

我的票是第三个选项,mouviciel贴然后将其删除:


  

我看到了第三种方式:

  // foo.h中
结构foo的;
无效doStuff(结构美孚* F);// foo.c的
结构foo的{
    INT X;
    诠释Ÿ;
};


如果你实在无法忍受键入结构关键字 typedef结构富富; (注意:获得去掉无用的和有问题的下划线)是可以接受的。但是,不管你做什么,从不使用的typedef 来定义指针类型的名字。它隐藏的信息极为重要的部分,这种类型的引用可能被修改的对象变量,只要你把它们传递给函数,它使具有不同资格的处理(例如,常量 -qualified)指针的版本,一个重大的痛苦。

I've seen both of the following two styles of declaring opaque types in C APIs. Is there any clear advantage to using one style over the other?

Option 1

// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);

// foo.c
struct foo {
    int x;
    int y;
};

Option 2

// foo.h
typedef struct _foo foo;
void doStuff(foo *f);

// foo.c
struct _foo {
    int x;
    int y;
};

解决方案

My vote is for the third option that mouviciel posted then deleted:

I have seen a third way:

// foo.h
struct foo;
void doStuff(struct foo *f);

// foo.c
struct foo {
    int x;
    int y;
};

If you really can't stand typing the struct keyword, typedef struct foo foo; (note: get rid of the useless and problematic underscore) is acceptable. But whatever you do, never use typedef to define names for pointer types. It hides the extremely important piece of information that variables of this type reference an object which could be modified whenever you pass them to functions, and it makes dealing with differently-qualified (for instance, const-qualified) versions of the pointer a major pain.

这篇关于不透明的C结构:应如何声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆