Looks like you defined the functions right in your header. For example, like this:
void foo() {
puts "Hello World!");
}
#include "foo.h"
#include "foo.h"
Note that #include is a preprocessor command, causing the preprocessor to copy the whole text contained in foo.h into each of the cpp file including it, so, after the prprocessor is done, the intermediate cpp files that you get look like this:
void foo() {
puts("Hello World!");
}
void foo() {
puts("Hello World!");
}
Now the compiler takes the processed version of foo.cpp, finds the function with the signature
void foo()
, and stores the signature of this function as well as the address of the binary code that it starts. Then the compiler picks the processed version of bar.cpp and does the same, ignorant of the code that went into foo.obj (no, the compiler does not keep track of other compiled modules!).
Then the linker steps up, and binds all modules into one executable. To do so it needs to create a table of all functions and the memory offsets to the start of these functions within the binary code. It picks up foo,obj and registers the function with the signature
void foo()
. Then it picks up bar.obj and tries to register the function foo() it finds there, but notices that a function by that signature already exists! Since the linker does not know whether the two versions of the binaries are identical, and it isn't clear which function to call, the linker, by itself cannot resolve this issue. Hence it issues the error, LNK2005.
There are a few exceptions: If you define a function as
inline
, then the preprocessor will not put the whole function into the source file that include the header, but instead will replace all calls to the function with the code of the functions body, much like a #define macro (but a lot safer). It also seems that defining member functions of a class right at the point where they are declared is also possible, although I am not sure if this is due to them being interpreted as inline, or whether functional code form classes is treated differently.
In short, you should not define functions in a header file! A header file is meant for declarations only. Move the definitions to a separate cpp file instead and your problem should be solved.