In fact, you should. If you don't, and instead put the implementation in the .h file, you can't include the header file more than once, lest you get a linker error about defining the same function twice.
Code:
$ cat header.h
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
class C {
public:
static void function();
};
void C::function() {
std::cout << "Hello, World!\n";
}
#endif
$ cat header.cpp
#include "header.h"
int main() {
C::function();
return 0;
}
$ cat header2.cpp
#include "header.h"
void another_function() {
C::function();
}
$ g++ header.cpp header2.cpp -o header
/tmp/ccTTAxaC.o: In function `C::function()':
header2.cpp:(.text+0x11c): multiple definition of `C::function()'
/tmp/cca6d8S9.o:header.cpp:(.text+0x11c): first defined here
collect2: ld returned 1 exit status
$
Incidentally, you can put the method body in a header file if it's inline:
Code:
dwk@cypress:~/c/cb$ cat header.h
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
class C {
public:
static void function() { std::cout << "Hello, World!\n"; }
};
#endif
$ g++ header.cpp header2.cpp -o header
$ ./header
Hello, World!
$