user1730056
user1730056

Reputation: 623

Defining a function that passes a struct in a C header

Having some trouble with headers. I have a header data.h that contains the struct information for typedef struct newPerson.

The data.h is used in my source menu.c. and in menu.c, I have a function, void addStudentRecord(newPerson pers). The code compiles and works like wanted.

However, I'm required to add all my functions to my menu.h header. When I add void addStudentRecord(newPerson pers); to my menu.h, I get this error unknown type name ‘newPerson’.

I tried to solve this by adding #include "data.h but that just gives me a shitload more errors. I was wondering how I would define a function that takes a struct in a header file?

Upvotes: 1

Views: 72

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754710

You can pass pointers to incomplete structure types to a function, but if you want to pass a copy of the structure, it must be a complete type. That is, you must have the complete struct structname { ... } definition visible to be able to pass copies of the structure.

The type defined in data.h appears to be an incomplete type, so you can't use that to declare functions that require a copy of the structure. But you probably want the functions to accept a pointer to the structure anyway.

See also:

Upvotes: 2

user3386109
user3386109

Reputation: 34839

Sounds like you need include guards. An include guard prevents the header file from being included multiple times.

For example, if you have menu.h which includes data.h, and you have menu.c which includes data.h and menu.h, then everything in data.h is included twice, which causes all sorts of errors.

By adding an include guard as shown below, you guarantee that the body of data.h is only included once

// data.h

#ifndef DATA_H
#define DATA_H

// the rest of data.h goes here

#endif /* DATA_H */

Some compilers allow you to use a #pragma once to do the same thing

// data.h

#pragma once

// the rest of data.h goes here

Upvotes: 0

Related Questions