1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user1730056
  • 623
  • 3
  • 11
  • 19
  • Passing a whole struct to a function is a very bad idea. such code causes the compiler to insert (at least) to calls to memcpy() and allocates some memory that is not accessable for anything else. strongly suggest just passing a pointer to the struct. Note: the struct does need to be defined (in the header file) before the prototype of a function that uses that struct – user3629249 Feb 21 '15 at 01:19

2 Answers2

2

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:

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

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
user3386109
  • 34,287
  • 7
  • 49
  • 68