简体   繁体   English

头文件2中需要头文件1中的struct,我该怎么做?

[英]struct in header file 1 needed in header file 2, how do I do that?

I have a struct that I use in header file1. 我有一个结构,我在头文件1中使用。 I now also need that struct in header file2 because it is used in function prototypes. 我现在还需要头文件2中的结构,因为它用在函数原型中。 I have included header file1 in header file2, but this give a lot of complaints of redefition of types after compiling? 我在头文件2中包含了头文件1,但这会在编译后给出很多关于类型重新定义的抱怨吗? Is there a straightforward way to do it? 有一种直截了当的方法吗? I have googled about nested header files but this gives me rather complicated articles. 我已经搜索了嵌套的头文件,但这给了我相当复杂的文章。 I was wondering if there is a simple way to do this? 我想知道是否有一种简单的方法可以做到这一点?

Sure there is. 当然有。 Use include guards . 使用包括警卫

file1.h

#ifndef FILE1_H
#define FILE1_H

/* Define everything here. */

#endif

This way you can include file1.h over and over. 这样你可以反复包含file1.h。 In particular, you should always use include guards if a header defines things. 特别是,如果标题定义了事物,则应始终使用包含保护。

As a side note, if you don't need the details of the struct (that is, it should be an opaque type), you can use an incomplete type and just say struct yourstruct; 作为旁注,如果您不需要结构的详细信息(也就是说,它应该是一个不透明的类型),您可以使用不完整的类型,只需说struct yourstruct; at the top. 在顶部。

I believe your header files are not guarded with include guards to prevent redefinitions. 我相信您的头文件没有防范包含防护以防止重新定义。 They should be 他们应该是

//header.h
#ifndef SOME_LONG_UNIQUE_NAME
#define SOME_LONG_UNIQUE_NAME

//header contents here

#endif

As a side note, you don't need all the header and struct definition just to declare function arguments. 作为旁注,您不需要所有头和结构定义来声明函数参数。 A forward declaration is enough. 前瞻声明就足够了。

struct C; //not including C.h
struct C* f(struct C* p);

This decreases code coupling and accelerated compilation 这减少了代码耦合和加速编译

Header file 1: 头文件1:

#ifndef HEADERFILE1_H
#define HEADERFILE1_H

//...
#endif

Header file 2: 头文件2:

#ifndef HEADERFILE2_H
#define HEADERFILE2_H

#include "headerfile1.h"

//...
#endif

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

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