Is it a good idea to describe functions in header files?

I've heard that you shouldn't. I'd rather have another way though, instead of cluttering all of the functions at the bottom of the cpp file, and that being half of the files length.
If you define your function in the header and it is not a template function and it is not an inline function, if you include that header in several cpps you'll get an 'multiple definitions' error.

Note that your program doesn't have to look like this:
1
2
//header.h
int function();

1
2
3
4
5
6
//main.cpp
#include "header.h"

int main(){ return function(); }

int function(){ return 5; }


It could look like this:
1
2
//header.h
int function();

1
2
3
4
//main.cpp
#include "header.h"

int main(){ return function(); }

1
2
3
4
//header.cpp
#include "header.h"

int function(){ return 5; }

That way you can keep your files small and clean.
Functions are declared or defined.

It is very good to declare them in header files. Defining them in header files depends on what you intend to do with them. If you're building a library, then a header file of declarations that people can #include, and a separate cpp file that gets compiled into the library, is quite sensible.

Remember, there's nothing stopping you having more than one cpp file. You could have your principal cpp file, containing your main function, and a header file declaring your additional classes and functions, and then another cpp file with the definitions in. Indeed, as many additional header and cpp files as you like, to organise the code sensibly.

Just have consideration for the people who will be using your code, and act accordingly. If it's a quick hack for you alone, no worries. If you're writing a commercial library, then a header file with the declarations and a set of cpp files to compile into the library seems sensible.

As counter example, look at easybmp; until version 1.something, it was a single large header file, because the target audience was people who needed a very simple way to manipulate bmp files, and the simplest way he could think of was a single header file to include.

Edit: The hamsterman beat me to it. Half man, half hamster, all programmer :p
Last edited on
What is you question exactly? When you say "describe functions" do you mean "document functions" or do you mean "define functions"?
Hm, I never considered using multiple cpp files. Thanks guys, again. I wish I could contribute back to this forum in some way.
And I meant defining, I get the terms for functions mixed up a lot of the time.
Boost is a good example of a major C++ project where most of the libraries are header only. This post does a good job of explaining why you might want to do that: http://lists.boost.org/Archives/boost/2008/04/136702.php
Topic archived. No new replies allowed.