[prog] [C/C++] what to put in header files.

Sujita Purushothaman sujita at mimos.my
Thu Sep 19 13:35:57 EST 2002


Akkana wrote:

> Sonja Krause-Harder writes:
> > To keep things tidy, I started to have a corresponding *.h for each
> > *.c file, and put every function prototype there. I also put all the
> > #include s I needed into the header file, and only #include this one
> > in the *.c file. While this is definitely neat and clean, it isn't
> > necessary all the time, and maybe a bit "chatty". Apart from that,
> > when I look at other projects, they don't usually do it that way, so
> > I'm wondering if there are some common rules how to organize
> > the header files, or if people are so used to grepping anyway that
> > it doesn't matter where to put things.
>
> One rule that really helps with compiling huge projects is that each
> include file should include as few other files as possible.  If class
> Foo uses class Bar, it's much better to include Bar.h in Foo.cpp rather
> than in Foo.h.  Why?  Because there may be fifty other files that
> include Foo.h, and for each one of those, if Foo.h includes Bar.h
> then the compiler has to open that file as well as Foo.h.  (Smart
> filesystem cacheing can help speed this up, as can precompiled headers,
> so the difference may or may not be large depending on the kernel,
> the compiler, available RAM, and how huge the project really is.)
>
> Those things you often see at the beginning and end of an include file:
>
> #ifndef FOO_H
> #define FOO_H
> [ ... body of file ... ]
> #endif /* FOO_H */
>

I  _always_ used to wonder why these things were used!! Thanks
so much!
<snip>

> Incidentally, the rule you're following, of having each .c file have a
> corresponding .h file (and, in C++, have one class per file pair with
> the file name the same as the class name), is another practice developed
> to make large projects easier.  I thought it was silly 'til the first
> time I had to come in on a large C++ project I didn't write; and then it
> made a surprisingly big difference being able to expect that if I'm
> looking for the DarkerShadeOfFoo class, I'll find its signature in
> DarkerShadeOfFoo.h and its implementation in DarkerShadeOfFoo.cpp
> instead of having to grep all over the whole class structure looking
> for it.
>

Yes, when I had to jump in halfway in a C++ project, this helped me
a lot too.

> (Having said that, I don't follow it consistently in my own little C
> projects.  Perhaps I should.  In any case it's a good idea in C++ in
> a project that might ever grow large and have multiple contributors.)
>

I don't think it's that important in C . C programs are more straightforward

in structure than C++! ( I hate C++! )

> > (Oh, and welcome to the list, all of you! ;-))
> Yay, a programming list!  Hi, everybody. :-)
>

Hi !!

Rgds,
Sujita




More information about the Programming mailing list