一种做c ++的方法"typedef struct foo foo;" 对于c

mhe*_*man 2 c c++ gcc typedef

按照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;
Run Code Online (Sandbox Code Playgroud)

在C++中是合法的但在C中则不合法.

当然,我有一个代码体,可以通过使用foo类型在C++中编译得很好,但看起来我必须使用struct foo(在头文件中)才能使它与另一个开发人员编写的一些C代码一起使用.

有没有一种方法,以预先声明一个结构类型定义FOO FOO在GCC C时不编译用于C时,会出现"类型定义'富’的重新定义"错误?(我不希望struct typedef _foo foo的边缘非法且不太干净的下划线解决方案)

Mik*_*ler 7

这是你需要的吗?

// header (.h)
struct foo;
typedef struct foo foo;

foo *foo_create();
// etc.

// source (.c)
struct foo {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我还倾向于在简化时使用下划线为我的结构名称添加前缀以使其私密性清晰并防止可能的名称冲突.

  • 使用下划线时请注意保留名称,请参阅http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac-identifier (2认同)

AnT*_*AnT 5

C++ 和 C 之间的区别之一是,在 C++ 中,typedef只要所有这些都是typedef等价的,在同一范围内进行重复是合法的。在C语言中重复typedef是非法的。

typedef int TInt;
typedef int TInt; /* OK in C++. Error in C */
Run Code Online (Sandbox Code Playgroud)

这就是您上面代码中的内容。如果您尝试编写可以编译为 C 和 C++ 的代码,请删除多余的第二个 typedef 并执行以下操作

typedef struct foo foo;  
...
struct foo  
{  
    int bar;  
};
Run Code Online (Sandbox Code Playgroud)

(尽管在 C++ 中,第一个typedef也是多余的)。