简体   繁体   English

C和C ++头文件:在另一个结构内部定义全局结构

[英]C and C++ header: Define global struct inside of another struct

I have some C code that has some structs that looks like this: 我有一些C代码,其某些结构如下所示:

typedef struct my_library_a_t my_library_a_t;
typedef struct my_library_b_t my_library_b_t;
typedef struct my_library_c_t my_library_c_t;

struct my_library_a_t {
    struct my_library_b_t {
        int data;
        struct my_library_c_t {
            int data;
        } c;
    } b;
    int data;
};

This doesn't work in C++, because in C struct my_library_b_t defines a global struct my_library_b_t , whereas in C++ it defines ::my_library_a_t::my_library_b_t . 这在C ++中不起作用,因为在C struct my_library_b_t定义了全局struct my_library_b_t ,而在C ++中,它定义了::my_library_a_t::my_library_b_t

How can I get the inner struct definition to define a global struct in C++? 如何获取内部结构定义以在C ++中定义全局结构? Or even just not have to change too much code for it to work (I don't mind having a #ifdef __cplusplus block, but I don't want to pull the structs out because the reason they are nested in the first place is that they are used only one time each, and it's really hard to read when the inner class definitions are above the outer class definitions) 甚至不必更改太多代码即可工作(我不介意拥有#ifdef __cplusplus块,但我不想拔出这些结构,因为它们嵌套在第一位的原因是它们每次仅使用一次,并且当内部类定义高于外部类定义时,这真的很难阅读)

I tried struct ::my_library_b_t in the definition, but this doesn't work. 我在定义中尝试了struct ::my_library_b_t ,但这不起作用。

For context, I'm parsing a string that has a definition that would look like this: 对于上下文,我正在解析一个具有如下定义的字符串:

a     = b "," data
b     = data "," c
c     = data
data  = %x31-39 *DIGIT  ; 1-9 followed by *(0-9)
      / "0"

And the intermediate parts have meaning, so it's useful to be able to have functions that take my_library_b_t* or my_library_c_t* . 而且中间部分具有含义,因此能够具有采用my_library_b_t*my_library_c_t*函数很有用。

I would prefer to have a solution that looks like this: 我希望有一个看起来像这样的解决方案:

#ifdef __cplusplus
#define GLOBAL_STRUCT(name) ???  (I tried `:: name`)
extern "C" {
#else
#define GLOBAL_STRUCT(name) name
#endif

struct my_library_a_t {
    struct GLOBAL_STRUCT(my_library_b_t) {
// ...

I recommend this 我推荐这个

struct my_library_a_t {
    struct my_library_b_t {
        int data;
        struct my_library_c_t {
            int data;
        } c;
    } b;
    int data;
};
#ifdef __cplusplus
    typedef struct my_library_a_t::my_library_b_t my_library_b_t;
    typedef struct my_library_b_t::my_library_c_t my_library_c_t;
#else
    typedef struct my_library_a_t my_library_a_t;
    typedef struct my_library_b_t my_library_b_t;
    typedef struct my_library_c_t my_library_c_t;
#endif

Notice that after alias my_library_b_t, you don't need to use my_library_a_t::my_library_b_t::my_library_c_t 注意,在别名为my_library_b_t之后,您无需使用my_library_a_t :: my_library_b_t :: my_library_c_t

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

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