I don’t quite understand how things should be separated in C’s source and header files. I often see many projects with two sets of files with the same name (an extension denotes a source and another donates a header file).
So far, from this lack of understanding, when I’ve written libraries, I’ve chucked all the class and class method code into one file, with indecision as to choosing the file extension.
What should be in headers and what should be in the source files? How do I implement this separation?
There is no technical difference. The compiler will happily let you include a
.cfile, or compile a.hfile directly, if you want to.There is, however, a huge cultural difference:
Declarations (prototypes) go in
.hfiles. The.hfile is the interface to whatever is implemented in the corresponding.cfile.Definitions go in
.cfiles. They implement the interface specified in the.hfile.The difference is that a
.hfile can (and usually will) be#included into multiple compilation units (.cfiles). If you define a function in a.hfile, it will end up in multiple.ofiles, and the linker will complain about a multiply defined symbol. That’s why definitions should not go in.hfiles. (Inline functions are the exception.)If a function is defined in a
.cfile, and you want to use it from other.cfiles, a declaration of that function needs to be available in each of those other.cfiles. That’s why you put the declaration in a.h, and#includethat in each of them. You could also repeat the declaration in each.cfile, but that leads to lots of code duplication and an unmantainable mess.If a function is defined in a
.cfile, but you don’t want to use it from other.cfiles, there’s no need to declare it in the header. It’s essentially an implementation detail of that.cfile. In that case, make the functionstaticas well, so it doesn’t conflict with identically-named functions in other files.