Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

header

typedef

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?

like image 239
rablentain Avatar asked Nov 21 '13 12:11

rablentain


People also ask

Where do I put typedef?

First way is to typedef at the place-of-first-declaration. Second way is to typedef at each place-of-use, and make it only visible to that place-of-use (by putting it inside the class or method that uses it).

Can you put definitions in header files?

Header files can include any legal C source code. They are most often used to include external variable declarations, macro definitions, type definitions, and function declarations.

What library is typedef in?

In the C standard library and in POSIX specifications, the identifier for the typedef definition is often suffixed with _t , such as in size_t and time_t .

Do struct definitions go in header files?

Structs should be defined in headers, unless they are local to specific file — a special occasion, prefer to define them in header, you can easily move them to implementation file later if needed.


1 Answers

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
like image 154
user694733 Avatar answered Oct 14 '22 08:10

user694733