15

I've defined a struct item in a .h file. Now I'm defining another struct tPCB in another .h which is part of the same project, and I need the tPCB to have an item. I thought that just making part of the same TurboC project would allow me to use item in the other header file, but the compiler throws me "undefined type: ite".

I guess I somehow have to include the first header on the second one, However I have seen the same a similar code which works without doing so.

Is there any other way than just adding an #include line to make it work?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
bluehallu
  • 10,205
  • 9
  • 44
  • 61

5 Answers5

15

If your .c #includes the two .h files in the proper order, it will work. That's probably what happened in the case you remember. The safest course is to #include every file that defines your dependencies, and rely on the include guards in each .h to keep things from being multiply defined.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • @nmichaels, thanks. Easy to fix, the advice remains the same regardless. – Mark Ransom Mar 17 '11 at 19:13
  • Ok, so I've moved the include to the first .h to the first line of the main .c, which I understand to be the first line to be read by the compiler, and the problem remains. – bluehallu Mar 17 '11 at 19:17
  • @Hallucynogenyc, you need to include both .h in your main .c. First is the one that defines `item`, next the one that defines `tPCB`. Better, put a `#include` into the .h that defines `tPCB`. – Mark Ransom Mar 17 '11 at 19:20
4

Sorry, there is no way in C that you can access a definition of a structure, in another header file without including that file (through an #include). Instructions for the #include follow.

So, lets say that the header file that contains the definition of the item structure is called "item.h", and the header file that contains the definition of the tPCB structure in "tPCB.h". At the top of tPCB.h, you should put the following statement:

#include "item.h"

This should give the tPCB.h file access to all the definitions in item.h.

Toast
  • 356
  • 1
  • 2
  • 8
2

Never ever put variable definitions (that is, allocating them) in a header file. That is bad for many different reasons, the two major ones being poor program design and floods of linker errors.

If you need to expose a variable globally (there are not many cases where you actually need to do that), then declare it as extern in the h-file and allocate it in the corresponding C file.

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

In your "another .h", #include <a .h file>.

Elaboration:

In the file that defines struct tPCB, you need to #include the file that defines struct item.

nmichaels
  • 49,466
  • 12
  • 107
  • 135
0

You need to use #include. In C, everything is explicit; don't expect it to work by magic.

metamatt
  • 13,809
  • 7
  • 46
  • 56