The answers saying "put just a declaration in a header file" are right, but it's also worth knowing that you can avoid a separate source file for the definition, and linking the corresponding .o
file, by putting this this in a header file:
inline int RandomRange(int min, int max)
{
int newValue = (rand() % max) + min;
// etc...
}
This is simpler, but means that every source file that includes the file will have to process the full definition when it's compiled, and also that every source file that includes this file will have to process <cstdlib>
, which this file needs to include in order to call rand()
.
For such a small function and for a header as basic as <cstdlib>
, it's premature optimization to worry about the effects of that on compilation time for a full build, although it will noticeably affect partial builds when this header file is changed. There are also some issues of functionality, though - if you do this then:
(a) object files that used this header file and are linked together must use identical definitions of RandomRange
, so a change to the contents of the function body breaks link-compatibility. And that's identical after pre-processing - there are no macros used in this example so it's the same either way, but it's possible to make mistakes here.
(b) you can't replace the definition of RandomRange
just by linking a different object file containing a different definition (for debugging, testing, or link-time application configurability).
For small functions and small projects, these drawbacks aren't normally a concern. For large functions and large projects, normally at least some of them are, which is why the standard safe thing is to have separate declarations and definitions.