Another ''alredy defined in .obj'' error

Started by
2 comments, last by SiCrane 11 years, 7 months ago
I have a ''Utility.h'' header that has 2 functions in it(fully defined with bodies and everything,since I won't be changing them anytime soon).Once I included them in my .cpp files,it gave me an error for each .cpp file like:

void_cdecl MyFunction(char const*, char const*, unsigned int) (?MyFunction@@YAXPBD00GI@Z) alredy defined in MyModule.obj.[/quote]
Every header file,including Utility.h has 2 include guards(pragma comment and ifndef) + it's only included in the cpp files,I don't understand why it would still give such an error.None of my other headers give such errors.
Advertisement
First your code is compiled. That means that every .cpp file is turned into a .obj file that contains machine language versions of all your code. Then your .obj files are linked. In this process, the linker checks what functions and variables your program needs and puts them into your .exe file. So, what happened here is you had two identical functions in two separate .cpp files (by inclusion) which in turn creates two identical functions in your .obj files. This confuses the linker because it doesn't know which one to choose so it throws an error. So, what you want to do is only declare your functions in your header and define the body in a single .cpp file. This causes the compiler to not throw errors because it knows what your functions look like but their bodies will be defined only once so you won't confuse the linker. If you won't be changing the code, just don't touch it. You can copy the .cpp file around into your next projects and whatnot, but always keep them in a separate file.
I was of the thought that as long as the code was completely identical it was okay. Did I read that wrong somewhere?
You can define functions in headers if they are explicitly or implicitly inlined. You explicitly inline them with the inline keyword. Implicitly inlined functions include member functions defined in class definitions and template functions. Inline functions must be identical in every translation unit they are defined in, otherwise bad juju happens.

This topic is closed to new replies.

Advertisement