1

I'm working on a fairly simple C program with a main file, vector.c, vector.h, but I'm running into these issues:

  • where do I put the include for a .h file if the declarations it provides are needed in both c files?
  • where do I put typedefs needed in all 3 files?

seems like gcc complains no matter what I do.

Can anyone answer these questions, or point me toward a resource I can read?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Colleen
  • 23,899
  • 12
  • 45
  • 75

2 Answers2

2

where do I put the include for a .h file if the declarations it provides are needed in both c files?

Put include statements in each C file that requires the header definitions, in your case, in main.c and vector.c. Using include guards is always a good idea, and required if the compiler is complaining about symbols being already defined or multiply defined.

where do I put typedefs needed in all 3 files?

It depends:

  • If the typedefs are necessary for, or specific to your vector API, then put them in vector.h.
  • If they have nothing to do with your vector interface, i.e. they're specific to main.c, then they probably belong there.
  • But you mention that they're needed for all 3 files, so if these typedefs aren't part of your vector interface then they probably belong to a 3rd header file, for example something like common.h, which might also be included by every other file in your project.
Community
  • 1
  • 1
pb2q
  • 58,613
  • 19
  • 146
  • 147
2

Very naturally:

  • You include the header from whichever C file(s) need it.
  • typedefs are declarations, so they are very well suitable to put in header files.

Sometimes you might need protection against multiple inclusion, if you have headers that include headers, but for your case that's not needed. Remember that every C file compiles on its own. Never use #include with C files, of course.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • +1 I would drop the "sometimes" bit, and point the OP to the description of inclusion guards: it is much easier to guard all headers as if they were included multiple times than to run in circles trying to figure out why your compilation started to break after someone else added an innocently-looking `#include` :) – Sergey Kalinichenko Jul 02 '12 at 15:32