Can anyone explain me why MinGW compiler gives multiple definition error about functions implemented in the two separate cpps and not declared in the headers?
Can anyone explain me why MinGW compiler gives multiple definition error about functions implemented in the two separate cpps and not declared in the headers?
If the functions wind up in the same linkage, there's going to be a conflict. You must differentiate functions by name, argument list, namespace or some other scoping mechanism if they will be combined into a single executable or library.
spirt (12th June 2011)
I thought that cpp already provides a separate scope, if function declared and implemented only there and not exported, there shouldn't be any problem
Well, you should be using a different class for the two seperate cpp files so this shouldn't be problem.
If you are using global functions then obviously defining the same function in two different cpp files will cause confusion at link time which to use, so either make one of them file local or put them in a class. Same goes for global variables. The linker is not going to check to see if you have included such functions in a header file.
Even though functions are implemented in two separate source files, if they belong to same namespace, the linker would be confused which one to use for linking and ends up in throwing error.Originally Posted by sprit
Yes both the functions have different scope (as not declared in include files), but scopes are different for compiler & linker. For compiler, scope is single translated unit (including any extern symbols). Linker's job is to connect all the translation units, to so form the final executable, so for linker the scope includes all translations units, and hence the error.Originally Posted by sprit
C++ provides various ways to deal with situation, like namespace separation, object encapsulation using classes / structs, function overloading etc, you can use one of these methods.
I'd suggest to use anonymous namespaces to avoid such conflicts:
Qt Code:
//a.cpp namespace { void function() {...} } //b.cpp namespace { void function() {...} }To copy to clipboard, switch view to plain text mode
Bookmarks