简体   繁体   English

我可以在 C 中 typedef struct aaa struct x_aaa 吗?

[英]Can I typedef struct aaa struct x_aaa in C?

I use a public library.我使用公共图书馆。 It change its struct from struct aaa to struct x_aaa in newer version.它在较新版本中将其结构从 struct aaa 更改为 struct x_aaa。 I want to keep my code pass compiling in any version of the library.我想在库的任何版本中保持我的代码传递编译。 So I want to do such:所以我想这样做:

#if lib_ver > 20000
typedef struct x_aaa struct aaa;
#endif

And then use strcut aaa in later code.然后在后面的代码中使用 strcut aaa 。 But this not work.但这行不通。 How do you solve such problem?你如何解决这样的问题?

A typedef name must be a single identifier, so you can't do that. typedef 名称必须是单个标识符,因此您不能这样做。
(A typedef has the same form as a variable declaration, with the word "typedef" added in front of it.) (typedef 与变量声明具有相同的形式,在其前面添加了“typedef”一词。)

You can use a typedef that depends on the version您可以使用取决于版本的 typedef

#if lib_ver > 20000
    typedef struct x_aaa lib_aaa;
#else
    typedef struct aaa lib_aaa;
#endif

and change your code to use lib_aaa instead of the full struct name.并更改您的代码以使用lib_aaa而不是完整的结构名称。

You could also use a macro, but it's a good idea to avoid them:您也可以使用宏,但最好避免使用它们:

#if lib_ver > 20000
    #define aaa x_aaa;
#endif

The renaming sounds like it could be a breaking change even if you get your code to compile, though.但是,即使您编译代码,重命名听起来也可能是一个重大更改。
I would be very cautious about this.我会对此非常谨慎。

You cannot typedef a struct something into struct something_else .你不能typedef一个struct somethingstruct something_else

What you can do is to typedef a struct something into something_else (dropping the word struct ).你可以做的是typedef一个struct somethingsomething_else (下降字struct )。

If this is not what you want, you should use a simple #define :如果这不是你想要的,你应该使用一个简单的#define

#define aaa x_aaa
typedef struct aaa bbb;
//      ^^^^^^^^^^      source type
//                 ^^^  new identifier

You can't have the new identifier for an existent type be "struct something".您不能将现有类型的新标识符设为“struct something”。

You maybe need to change the code to reflect that the struct you're using is not the same in all versions of the library您可能需要更改代码以反映您使用的结构在所有版本的库中都不相同

#if lib_ver > 20000
#typedef struct x_aaa libaaa
#else
#typedef struct aaa libaaa
#endif

// in your code use `libaaa` instead of `struct aaa`
//struct aaa foo;
libaaa foo;
//struct x_aaa bar;
libaaa bar;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM