0

I currently have many definitions of individual functions and each of them is in its own .h file

do I have to create a .h and a .cpp file to define a single function?

For example, do I have to do this for each function?:

//InsertionSort.h
#ifndef INSERTIONSORT_H
#define INSERTIONSORT_H

template <class T>
void InsertionSort(T A[], short n)

#endif
//InsertionSort.cpp
template <class T>
void InsertionSort(T A[], short n){
    T key;
    for (short j=1, i; j<n; j++){
        key = A[j];
        i=j-1;
        while(i>=0 && A[i] > key)
            A[i-- +1] = A[i];
        A[i+1] = key;
    }
}
Lurù
  • 31
  • 5
  • 4
    It's kinda funny, because you chose the one example where you *cannot* use separate .cpp file. [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Yksisarvinen Oct 31 '21 at 17:52
  • What if I don't have a template function instead? – Lurù Oct 31 '21 at 17:53
  • 1
    The answer to your question is "No". Separating code into .h and .cpp files is merely a tool for organizing your code and maintaining the [one definition rule](https://stackoverflow.com/questions/4192170/what-exactly-is-one-definition-rule-in-c#:~:text=No%20translation%20unit%20shall%20contain,that%20program%3B%20no%20diagnostic%20required). It is for your convenience. By comparison, some libraries ship as a single header file. – Drew Dormann Oct 31 '21 at 17:56
  • `#include` directive is a very simple copy and paste. It copies and pastes content of a file into another file. So you could do that manually and just type definitions into each file that needs them. Not a good idea if you have more than 2 files in the project, but possible. If you need function only in a single file, don't expose it in header file (unless it's a `private` class method). And group similar methodss in single header, no one wantts to `#include` a dozen of headers to get all mathematical operations. – Yksisarvinen Oct 31 '21 at 18:02
  • @Yksisarvinen if the functions are very different from each other, is it still a good idea to group their declarations in a header file? (instead of creating one for each file) – Lurù Oct 31 '21 at 18:13
  • @Eit There is no "one rule fits all". For small toy projects it probably doesn't matter. For bigger ones, you may try to think what will be useful for the user of this header. If they will use function `foo`, will they want to use `bar` in the same place? Does it make sense to group some functions (see `` or `` standard libraries)? It pretty much boils down to experience and code review from your peers – Yksisarvinen Nov 01 '21 at 16:16

0 Answers0