如何在 C 中的头文件中初始化结构体?
我正在尝试将一些旧代码从 20 年历史的 DOS 系统移植到 GNU Linux 系统。在它们的几个头文件(到处都有)中,它们具有声明和初始化的结构体。当我使用遗留代码的编写方式进行编译时,我收到警告。关于如何让它在同一个头文件中工作的任何提示?
以下是我根据他们正在做的事情制作的一个简化示例。
struct A
{
struct B temp1;
struct C temp2;
};
struct B
{
int temp3;
int temp4;
int temp5;
};
struct C
{
int temp6;
int temp7;
int temp8;
};
//These are the variables in how they are related to the initialization below
//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};
struct A test_one = {{1,2,3},{4,5,6}};
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system. In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize. I am getting warnings when I compile with the way the legacy code was written. Any tips on how I can get this to work with staying inside the same header file?
The following is a simplified example I made of what they are doing.
struct A
{
struct B temp1;
struct C temp2;
};
struct B
{
int temp3;
int temp4;
int temp5;
};
struct C
{
int temp6;
int temp7;
int temp8;
};
//These are the variables in how they are related to the initialization below
//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};
struct A test_one = {{1,2,3},{4,5,6}};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该实例化头文件中的任何结构。如果您这样做,将在您包含标头的每个 C 文件中创建不同的实例,通常不会达到预期的效果。
要在 C 文件中执行此操作,您必须执行以下操作。
我强烈考虑制作与此类似的辅助函数,然后考虑使用联合。
如果您希望保留数组初始化语法,那么
You shouldn't instantiate any structures in header files. If you do a different instance will be created in each C file you include the header in which is usually not the desired effect.
In a C file to do this you would have to do the following.
I would strong consider making helper functions similar to this
If you would like the keep the array initialization syntax then consider using a union.
在 A 之前声明结构体 B 和 C,即:
Declare struct B and C before A, i.e. :
您发布的代码不可编译,因为使用不完整类型来声明 struct 成员是非法的。我假设您只是错误地排列了
struct
定义:B
和C
的定义应该放在第一位。话虽如此,此代码可以生成的唯一警告是来自链接器的“警告”,如果头文件包含在多个翻译单元中,则链接器可能会抱怨同一对象
test_one
的多个定义。在 C 中,这在技术上是非法的,尽管许多编译器允许它作为流行的编译器扩展。那么,您收到什么“警告”?
The code you posted is not compilable, since it is illegal to use incomplete type to declare
struct
members. I assume that you simply misarranged yourstruct
definitions: the definitions forB
andC
should go first.Having said that, the only warning this code can generate is the "warning" from linker that might complain about multiple definitions of the same object
test_one
, if the header file is included in multiple translation units. In C this is technically illegal, although many compilers allow it as a popular compiler extension.So, what "warnings" are you getting?