How do I refer to a typedef in a header file?

♀尐吖头ヾ 提交于 2020-04-06 03:11:16

问题


I have a source file where a typedef struct is defined:

typedef struct node {
    char *key;
    char *value;
    struct node *next;
} *Node;

In this module, there are some functions that operate on a Node and have Node as return type. What am I supposed to write in the header file for this typedef?

Is it correct to write just

typedef *Node;

in the header?


回答1:


You can use:

typedef struct node * Node;

But I would advise against hiding the pointer in type declaration. It is more informative to have that information in variable declaration.

module.c:

#include "module.h"
struct node {
    char *key;
    char *value;
    struct node *next;
};

module.h:

typedef struct node Node;

variable declaration for pointer somewhere:

#include "module.h"
Node * myNode; // We don't need to know the whole type when declaring pointer



回答2:


The declaration

typedef *Node;

is invalid. It's missing the type. A good way to look at typedef is to remember it is just a storage class specifier, thus, it works like any other declarations. If you want to create an alias Node for the type struct node *, just declare a node pointer and name it Node:

struct node *Node;

And now prepend a typedef keyword:

typedef struct node *Node;

In general, to create an alias for a type, you just declare a variable of that type with the same name as the alias name you wish, and then prepend a typedef keyword. Even complicated typedef declarations can be easily approached like this.

So, typedef *Node; is invalid, it's like writing just j; without actually specifying its type.

Now, you can't typedef something twice. Either you will have to take the typedef out of struct node declaration and move it to the header file, or you move the whole typedef + structure declaration to the header file. The former solution is generally what you want, since it allows you to have some information hiding. So, my suggestion is to write this in the header file:

typedef struct node *Node_ptr;

And keep this in the source file:

struct node {
    char *key;
    char *value;
    struct node *next;
};

Note that I created the alias Node_ptr, not Node. This is good practice, to convey the idea that Node_ptr is a pointer.



来源:https://stackoverflow.com/questions/20120833/how-do-i-refer-to-a-typedef-in-a-header-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!