gpt4 book ai didi

c++ - 在 C++ 中使用 C 风格的 struct/typedef

转载 作者:可可西里 更新时间:2023-11-01 18:25:55 26 4
gpt4 key购买 nike

我有一个混合使用 C 和 C++ 的项目。在 C 头文件中,我有这样的代码:

typedef struct mystruct* mystruct;
struct mystruct {
// whatever struct needs
};

为了在 C++ 文件中使用它,我正在做:

extern "C" {
#include "mystruct.h"
}

所以你看到我正在创建一个使用相同名称的不透明指针。这在 C 中很好,但在 C++ 中不行(因为要求在 C 中使用 struct 关键字实例化,但在 C++ 中不行)。但是,在尝试编译 C++ 代码时出现错误(声明冲突)。我认为使用 extern "C" 会使编译器将 C header 视为 C,但它似乎仍将其用作 C++。对这里发生的事情有任何解释吗?

最佳答案

I thought that using the extern "C" would make the compiler treat the C header as C

没有。 extern "C" 做的唯一一件事就是控制名称修改。代码仍被编译为 C++(尽管 namespace 或模板等需要错位名称的内容将不起作用)。特别是,有关 struct 标识符的规则仍然适用。

关于c++ - 在 C++ 中使用 C 风格的 struct/typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6670779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com