Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I include <stdio.h> in my header file, just so I can declare a function that takes a FILE*?

For example in foo.h:

typedef struct foo_t foo_t;

/* Lots of function declarations dealing with foo_t... */

int foo_print(const foo_t *foo); /* Print foo to stdout. */
int foo_fprint(FILE *f, const foo_t *foo); /* Print foo to file f. */

I don't want to litter foo.h with too many other header files that users of foo.h might not have wanted to include, but I do need to declare functions that take types such as FILE*. I doubt that I am the first to encounter this dilemma, so what do people usually do in these circumstances? Or am I misguided in wanting to avoid including stdio.h in my header files?

EDIT:

People seem not to be understanding my question. To clarify, here are some potential solutions:

  1. Just include stdio.h and not worry about it causing conflicts in my clients' code (such as if they happened to have their own function that happened to be called getchar).
  2. Use an #ifdef to find out if stdio.h had already been included, and only then declare the FILE*-related functions. The downside of this is that it would impose a particular ordering to #includes in my clients' code.
  3. Move all I/O-related declarations to a separate header file such as foo_io.h.

What question is what is the best thing to do?

like image 437
Matt Avatar asked Feb 16 '15 17:02

Matt


1 Answers

Short answer: you are trying to solve a non-existing problem.

If you use FILE, you include stdio.h or cstdio in C++. It's that simple.

Trying to "optimize" #includes, besides obvious cases of unused ones, will not buy you anything and cause problems.

like image 181
ezaquarii Avatar answered Oct 14 '22 04:10

ezaquarii