简体   繁体   English

结构的定义应该在哪里用C声明? .c或.h?

[英]Where should be the definition of a struct be declared in C? .c or .h?

When implementing an ADT in C, I always thought that the definition of the struct should be in the .c file so that it was private. 当用C实现ADT时,我一直认为该struct的定义应该在.c文件中,以便它是私有的。 And in the typedef should be placed in the .h file so that other modules could use the ADT but could not modify its attributes directly. 并且应该将typedef放在.h文件中,以便其他模块可以使用ADT但不能直接修改其属性。 I recently ran into a problem and I had to move the struct to the .h . 我最近遇到了一个问题,不得不将结构移到.h I also found an answer Error: In C, got the error "dereferencing pointer to incomplete type" in a struct pointer where it is said that the struct should be defined in .c file. 我还找到了一个答案错误:在C语言中,结构指针出现错误“将指针解引用为不完整类型”,其中该struct应在.c文件中定义。 Is this true? 这是真的? If it is, what is the reason? 如果是,原因是什么?

As I noted in a comment : 正如我在评论中指出的:

The structure definition for an ADT should usually be in the source ( .c ) file that defines the support functions, and only a declaration of the type should exist in the header ( .h ) file. ADT的结构定义通常应该在定义支持功能的源文件( .c )中,并且头文件( .h )中应该只存在类型的声明。

However, that means you cannot allocate instances of the structure outside the source file defining the ADT. 但是,这意味着您无法在定义ADT的源文件之外分配该结构的实例。 You can only define pointers to the ADT outside. 您只能在外部定义指向ADT的指针。

If you had to move the definition from source to header, that means that something was not using a pointer that should have been using a pointer. 如果必须将定义从源移动到标头,则意味着某些东西没有使用应该使用指针的指针。 Go back and fix the broken code, and move the structure definition back into the source file for the ADT. 返回并修复损坏的代码,然后将结构定义移回到ADT的源文件中。

And, confirming what Nevado notes in a comment , it also means you cannot have an array of the ADT; 并且,确认Nevado注释中指出的内容,这还意味着您无法拥有ADT数组; you can have arrays of pointers to the ADT, but not arrays of the ADT itself. 您可以具有指向ADT的指针数组,但不能具有ADT本身的数组。

Note that it is perfectly legitimate to expose the structure if that's what you wish, or need, to do. 请注意,如果您希望或需要这样做,则公开结构是完全合法的。 That then allows you to create variables of the data type, or arrays of them, or to embed the type (rather than a pointer to the type) in other structures, etc. You lose some control; 然后,您可以创建数据类型或它们的数组的变量,或者将类型(而不是指向类型的指针)嵌入其他结构中,等等。 the programmer writing the code that uses the structure can see the details and could access (read or modify) the structure elements directly. 编写使用该结构的代码的程序员可以看到详细信息,并且可以直接访问(读取或修改)结构元素。 Cautious programmers won't do that unnecessarily, but it opens up possibilities precluded by the strict ADT idiom — at the risk of mistakes being made. 谨慎的程序员不会做不必要的事情,但是它开辟了严格的ADT习惯所无法提供的可能性-容易出错。

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

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