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

39,308

Solution 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

Solution 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.

Share:
39,308
rablentain
Author by

rablentain

Updated on November 22, 2020

Comments

  • rablentain
    rablentain over 3 years

    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?

  • Potatoswatter
    Potatoswatter over 10 years
    Or typedef struct node node; and be rid of the caps weirdness.
  • user694733
    user694733 over 10 years
    @Potatoswatter True. I just didn't wan't to confuse him/her by changing his/her naming conventions.