简体   繁体   English

C语言中的前向声明

[英]Forward Declaration in C

I wanted to ask about Forward Declarations in C. How generally they work. 我想问一下C中的前向声明。 For example if in a file I declare 例如,如果我在文件中声明

struct task_struct;

and define the struct in other file will it work? 并在其他文件中定义该结构是否有效? Because as far as I know Compiler must know the size of variable that is being declared. 因为据我所知,编译器必须知道要声明的变量的大小。 If it does then how does compiler actually handles such type of requests? 如果是这样,那么编译器实际上如何处理此类请求?

I found the above example in Linux Source code that got me interested. 我在Linux源代码中找到了上面的示例,这引起了我的兴趣。

Once you use a forward declaration, the type becomes Incomplete type for the compiler. 一旦你开始使用前向声明, 类型变得不完全类型的编译器。
Compiler does not know anything about the size or layout of the type and hence you cannot perform any operation which needs the compiler to know these. 编译器对类型的大小或布局一无所知,因此您无法执行任何需要编译器知道这些操作的操作。

In C, If you forward declare a type, you can only use a pointer to that type. 在C中,如果向前声明一个类型,则只能使用指向该类型的指针。 Since pointers to all structure types need same size [Note] , the compiler is just happy to know that it has a pointer to a type. 由于指向所有结构类型的指针需要相同的大小[注] ,因此编译器很高兴知道它具有指向类型的指针。

If I forward declare a structure and define it other file will it work? 如果我向前声明一个结构并定义它,其他文件将起作用吗?

It will as long as you only use a pointer to the structure in the file which forward declares the structure. 只要您仅使用指向向前声明结构的文件中的结构的指针即可。 If you dereference the pointer you will get errors, Since compiler is not aware of the layout of the Incomplete type. 如果取消引用指针,则会出现错误,因为编译器不知道Incomplete类型的布局。


[Note] Thanks to melpomene & Daniel for this clarification. [注意]感谢melpomene和Daniel的澄清。

What does "work" mean? “工作”是什么意思? Either way it will work in its own way. 无论哪种方式,它都会以自己的方式工作。

At the point where the full declaration of struct type is not visible, it is an incomplete type and is usable as incomplete type only. 在看不到struct类型的完整声明时,它是不完整类型,只能用作不完整类型。

At the point where the full declaration of struct type is visible, it becomes a complete type and is usable as complete type. 在可以看到struct类型的完整声明时,它成为完整类型,可以用作完整类型。

That's all there is to it. 这里的所有都是它的。

The usability of incomplete struct types is significantly reduced compared to complete ones. 与完整结构类型相比,不完整结构类型的可用性大大降低。 Basically, you can only declare pointers to such types and pass them around. 基本上,您只能声明指向此类的指针并传递它们。 Anything else (like declaring an object of that type) will require the full declaration. 其他任何事情(例如声明该类型的对象)都需要完整的声明。

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

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