代码之家  ›  专栏  ›  技术社区  ›  mheyman

C++的“TyPulfFraseFooFo”的一种实现方法

  •  2
  • mheyman  · 技术社区  · 15 年前

    根据GCC 4.4.2版,似乎

    typedef struct foo foo;
    // more code here - like function declarations taking/returning foo*
    // then, in its own source file:
    typedef struct foo
    {
        int bar;
    } foo;
    

    在C++中是合法的,但在C.不是合法的。

    当然,我有一个代码体,它通过使用C++来编译C++中的精细代码。 类型,但似乎我必须使用它 结构体 (在头文件中)让它与其他开发人员编写的一些C代码一起工作。

    有没有方法预先声明 结构typedef foo foo 在gcc c中,为c编译时没有得到“typedef'foo'的重新定义”错误?(我不希望有轻微违法和不太干净的强调解决 结构typedef foo foo )

    3 回复  |  直到 15 年前
        1
  •  3
  •   AnT stands with Russia    15 年前

    C++和C的区别之一在于C++中重复使用是合法的。 typedef 在同一范围内,只要所有这些 类型定义 是等效的。C重复 类型定义 是非法的。

    typedef int TInt;
    typedef int TInt; /* OK in C++. Error in C */
    

    这就是上面代码中的内容。如果你试图编写一个代码,可以编译为C和C++,摆脱多余的第二个TyPulf,只做

    typedef struct foo foo;  
    ...
    struct foo  
    {  
        int bar;  
    };
    

    (虽然在C++中是第一个 类型定义 也是多余的)。

        2
  •  7
  •   Mike Weller    15 年前

    这就是你需要的吗?

    // header (.h)
    struct foo;
    typedef struct foo foo;
    
    foo *foo_create();
    // etc.
    
    // source (.c)
    struct foo {
        // ...
    }
    

    在打字时,我还倾向于在结构名称前面加下划线,以使其私密性清晰,并防止可能的名称冲突。

        3
  •  0
  •   Jason Orendorff Oliver    15 年前

    我不知道为什么GCC拒绝这个代码,但它看起来只是对象,因为您定义了两次相同的typedef。

    这工作:

    typedef struct foo foo;
    
    struct foo {
        int bar;
    };
    

    这同样有效,效果也一样:

    typedef struct foo {
        int bar;
    } foo;