Sign in to follow this  
mrheisenberg

Another ''alredy defined in .obj'' error

Recommended Posts

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:

[quote]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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this