I have these .CPP files ("Main.cpp" and "RandomFunction.cpp"):
But when I launch the program, the compiler gives me a linker error: "RandomFunction.obj : error LNK2005: "void __cdecl randomFunction(void)" (?randomFunction@@YAXXZ) already defined in Main.obj"
// Do some stuff
So how should I rewrite the code to fix the linker error (I think I should define somewhere the extern function)?
You don't include .cpp files. You include .h files (which should just contain the prototype of the function, not the function itself).
It means you have to have (additionally) the following file
Originally Posted by tabstop
and include it instead of cpp
Aha, so .CPP files should NEVER be included.
Now I can place the function prototype in some header file, let's say "RandomFunction.h".
But where can I place the WHOLE DEFINITION of that function? Because I don't want to have it in the "Main.cpp" file. Could you please write here the code?
in RandomFunction.cpp, just like you have it now.
Originally Posted by Petike
Thanks you very much.
One more question...
I would have one more question:
Should I use in the "RandomFunction.cpp" also the #include "RandomFunction.h" directive or it will be enough to use it just in the "Main.cpp" file?
It is always a good idea to include the "x.h" in "x.c" or "x.cpp".
There are two reasons:
1. You want to make sure that both declaration and definition of the function is the same. If you only have the one or the other, the compiler may not be able to spot the difference between the one in the header file and in the source. By including the header in the source, the compiler will say "Ah, I've seen this function before, let's make sure it matches".
2. In more advanced programming, it is probably necessary to do so, because you would have type declarations (structs, classes, etc) that you need to have in both places [and the goal of programming is to reduce duplication].