How to find the multiple definitions of a function - c++

I wrote a findDialog which finds the text searched. When I give make command,it returns
g++ -Wl,-O1 -o findDialog FindDialog.o main.o moc_FindDialog.o -L/usr/lib -lQtGui -lQtCore -lpthread
moc_FindDialog.o: In function `FindDialog::findClicked()':
moc_FindDialog.cpp:(.text+0x20): multiple definition of `FindDialog::findClicked()'
FindDialog.o:FindDialog.cpp:(.text+0x30): first defined here
moc_FindDialog.o: In function `FindDialog::enableFindButton(QString const&)':
moc_FindDialog.cpp:(.text+0x50): multiple definition of `FindDialog::enableFindButton(QString const&)'
FindDialog.o:FindDialog.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [findDialog] Error 1
I have searched the problem for hours, but I can not understand what the problem stems from.
What can cause multiple definition of error?

It usually happens when method definition is included in multiple translation units, also called as object files. Later, when linker is combining those object files, it finds out that there are multiple definitions of the same method, and complains because it doesn't know which one to use. Here is a simple example of how to introduce this error:
Have header file header.hpp with both method declaration and its definition:
class foo {
public:
void bar ();
};
void foo::bar ()
{
}
And have two source files source1.cpp and source2.cpp both including that file:
source1.cpp:
#include "header1.hpp"
int example1()
{
foo f;
f.bar ();
}
... and source2.cpp:
#include "header1.hpp"
int main ()
{
foo f;
f.bar ();
f.bar ();
}
Then, compile two files separately and link them together. For example:
g++ -c source1.cpp source1.o
g++ -c source2.cpp source2.o
g++ -o a.out source1.o source2.o
That will give you a linker error you have described in your question, because method foo::bar appears twice, in both source1 and source2 objects. Linker doesn't know which one to use.
There are two common solutions to this problem:
Solution #1 - Have that method inlined.
By declared that method with inline keyword, compiler will either inline the whole method or, if it decides not to, it will generate anonymous method (same method but with some unique name for a given object file), so there will be no conflicts in object files. For example:
class foo {
public:
void bar ();
};
inline void foo::bar ()
{
}
Solution #2 - Have definition (implementation) of that method in another source file, so that it appears only once in the whole program. For example:
header1.hpp:
class foo {
public:
void bar ();
};
header1.cpp:
#include "header1.hpp"
void foo::bar ()
{
}
To decide whether to inline or not, you have to know (or at least make a guess) whether calling this function is more expensive than having this code duplicated / inlined all over the program. Inlined code usually makes your program bigger and increases compilation time. But it doesn't necessarily make it faster. Plus, having definition in source file will not result in re-compilation of all source files using that function, but only re-compilation of the source file that has definition, and then re-linking. Many programmers are going crazy about C++ inlining without really understanding how it affects the program. I'd recommend going with the definition in a source file and making it inline only if calling that function becomes a performance bottleneck and otherwise having it inlined will fix it.
Hope it helps. Happy coding!

Writing function definitions in header files, and then #includeing these header files in multiple .cpps in your project. Contrary to popular misconception, header guards do not protect you from this.
Write only the following in headers:
Class definitions
May include inline definitions for member functions
Non-member variable declarations
Non-member function declarations
Template/inline function definitions
Put everything else in "source files".

Vlad Lazarenko's answer is good.
I just add another possibility that I met when using QT/C++:
When you declare a slot, you don't need to write a definition (implementation), otherwise, you will get an error: multiple definition

Judging from file names in the error messages, you have some mock test fixtures as part of TDD and some real code. The linker did report where the trouble is fairly clearly - I've reformatted the information here for extra clarity by removing part of the information:
moc_FindDialog.cpp: multiple definition of `FindDialog::findClicked()'
FindDialog.cpp: first defined here
moc_FindDialog.cpp: multiple definition of `FindDialog::enableFindButton(QString const&)'
FindDialog.cpp: first defined here
This clearly states that the linker first encountered each of the function definitions in moc_FindDialog.cpp, and then encountered the second definition in FindDialog.cpp.
I think you need to look hard at the mock test fixture in moc_FindDialog.cpp and determine why those two functions are replicated. Or, maybe you are not supposed to link both the mock functions and the real functions in a single program - the two source files are simply not intended to be linked into a single program.

Related

C++ Error: Multiple definitions of class functions [duplicate]

This question already has answers here:
multiple definition error including c++ header file with inline code from multiple sources
(6 answers)
Closed 5 years ago.
I have a C++ classe in a .h file like this:
#ifndef __GLWidget_h__
#define __GLWidget_h__
class PivotShape
{
// This is allowed
void do_something() { std::cout << "Doing something\n"; }
// This is not allowed
void do_something_else();
}
// This is not allowed
void PivotShape::do_something_else()
{
std::cout << "Doing something else\n";
}
#endif
If I add methods inside the class declaration everything seems fine. But if I add methods outside of the class declaration, I get errors like this:
/usr/share/qt4/bin/moc GLWidget.h > GLWidget_moc.cpp
/programs/gcc-4.6.3/installation/bin/g++ -W -Wall -g -c -I./ -I/usr/include/qt4 GLWidget_moc.cpp
/programs/gcc-4.6.3/installation/bin/g++ main.o GLState.o GLWidget.o MainWindow_moc.o GLWidget_moc.o -L/usr/lib/x86_64-linux-gnu -lQtGui -lQtOpenGL -lQtCore -lGLU -lGL -lm -ldl -o main
GLWidget.o: In function `std::iterator_traits<float const*>::iterator_category std::__iterator_category<float const*>(float const* const&)':
/home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: multiple definition of `PivotShape::do_someting_else()'
main.o:/home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: first defined here
I think the duplication is being caused by this snippet in the Make file. I think the .h files are being converted to _moc.cpp files and this is allowing the multiple inclusions:
# Define linker
LINKER = /programs/gcc-4.6.3/installation/bin/g++
MOCSRCS = $(QTHEADERS:.h=_moc.cpp)
# Define all object files to be the same as CPPSRCS but with all the .cpp
# suffixes replaced with .o
OBJ = $(CPPSRCS:.cpp=.o) $(MOCSRCS:.cpp=.o)
Is this the problem? If so, how can I fix it? If not, what's going on?
I thought it was illegal in C++ to include class methods inside the body of the class declaration. If this is legal, then it seems like an easy way to solve the problem. Is this legal?
Edit:
I forgot to mention that I had already discovered that declaring the methods as inline works, but I was wondering how to avoid the duplication.
You're breaking the One Definition Rule; defining the function in the header means there's a definition in every translation unit that includes the header, and you're usually only allowed a single definition in the program.
Options:
Move the function definition into a source file, so there's just one definition; or
Add inline to the function definition, to relax the rule and allow multiple definitions; or
Define the function inside the class, which makes it implicitly inline. (To answer your final question, yes that is legal.)
Also, don't use reserved names like __GLWidget_h__.
Define the function in a source file or use inline to define it in the header file, outside the class definition.
Note that you can still define it inside the class definition without the inline keyword.
Related: Member function definition

How to find duplicate definitions from template specializations?

I have a template class with a specialization, defined in another file. Therefore it is possible to generate two versions of the same class: one time by replacing the template parameter and one time using the specialization. My current understanding is, that this can lead to two instanciations of the same type to have different sizes in memory, resulting in segmentation faults.
I created a minimal example and the following code is to illustrate the question:
Create a template class:
// - templateexample.h ---------------
#ifndef TEMPLATEEXAMPLE_H
#define TEMPLATEEXAMPLE_H
template<typename T> class Example
{
public:
Example(){}
int doWork() {return 42;}
};
#endif
// -----------------------------------
Template specialization in another file:
// - templatespecialization.h --------
#ifndef TEMPLATESPECIALIZATION_H
#define TEMPLATESPECIALIZATION_H
#include "templateexample.h"
template<> class Example<int>
{
public:
Example() : a(0), b(1), c(2), d(3) {}
int doWork() {return a+b+c+d;}
private:
int a; //<== the specialized object will be larger in memory
int b;
int c;
int d;
};
#endif
// --------------------------------
Have a class which includes only the template class definition, but should include the specialization.
// - a.h --------------------------
#ifndef A_H
#define A_H
#include "templateexample.h"
class A
{
public:
Example<int> returnSmallExample();
};
#endif
// - a.cpp ------------------------
#include "a.h"
Example<int> A::returnSmallExample() {return Example<int>();}
// --------------------------------
The main class now knows two versions of Example<int> the one from A and the one from the templatespecialization.h.
// - main.cpp ---------------------
#include <iostream>
#include "a.h"
#include "templatespecialization.h"
int main()
{
A a;
Example<int> test = a.returnSmallExample();
std::cout<<test.doWork()<<std::endl;
}
// --------------------------------
Please note, this problem will only occur when compiling class A separately, this example from ideone outputs 6, whereas using separate files can result in a segmentation fauls, or output 42 (https://ideone.com/3RTzlC). On my machine the example compiles successfully and outputs 2013265920:
In the production version of the above example everything is build into a shared library which is used by main.
Question 1: Why doesn't the linker detect this problem? This should be easy to spot by comparing the size of objects.
Question 2: is there a way to examine the object files or the shared library to detect multiple implementations of the same type like in the example above?
Edit: please note: the code above is a minimal example to explain the problem. The reason for the situation is that the template class is from one library and I cannot edit the files from this library. Finally the whole thing is used all over the place in the executable and now I need to find out if the problem above occurs.
Edit: code above can be compiled like this:
#!/bin/bash
g++ -g -c a.cpp
g++ -g -c main.cpp
g++ -o test a.o main.o
You have different definition of the same template and its specializations in different translation units. This leads to One Definition Rule violation.
A fix would be to put the specialization in the same header file where the primary class template is defined.
Question 1: Why doesn't the linker detect this problem? This should be easy to spot by comparing the size of objects.
Different types may have the same size (e.g. double and int64_t), so, obviously, just comparing sizes of objects does not work.
Question 2: is there a way to examine the object files or the shared library to detect multiple implementations of the same type like in the example above?
You should use gold linker for linking your C++ applications, if you do not use it already. One nice feature of it is --detect-odr-violations command line switch which does exactly what you ask:
gold uses a heuristic to find potential ODR violations: if the same symbol is seen defined in two different input files, and the two symbols have different sizes, then gold looks at the debugging information in the input objects. If the debugging information suggests that the symbols were defined in different source files, gold reports a potential ODR violation. This approach has both false negatives and false positives. However, it is reasonably reliable at detecting problems when linking unoptimized code. It is much easier to find these problems at link time than to debug cases where the wrong symbol.
See Enforcing One Definition Rule for more details.
Question 1: Why doesn't the linker detect this problem? This should be easy to spot by comparing the size of objects.
Because this is not a linker's problem. In case of templates, the main declaration and all the other specializations (be it class or function) should be visible upfront.
Question 2: is there a way to examine the object files or the shared library to detect multiple implementations of the same type
like in the example above?
At least I am not aware of any.
To further simplify this situation, look at a similar broken code:
// foo.h
inline void foo () {
#ifdef FOO
return;
#else
throw 0;
#endif
}
// foo1.cpp
#define FOO
#include"foo.h"
// ... uses foo() with "return"
// foo2.cpp
#include"foo.h"
// ... uses foo() with "throw"
It's possible that you get different results based on the way of compilation being used.
Update:
Having multiple body definitions for a same function is undefined behavior. That's the reason why you are getting an awkward output like 2013265920 and the same happens in my machine as well. The output should be either 42 or 6. I gave you above example because with inline functions you can create such race conditions.
With my limited knowledge on linking stage, the responsibility undertaken by a typical linker is limited only till rejecting more than 1 non-inline functions definitions with the same signature. e.g.
// Header.h is included in multiple .cpp files
void foo () {} // rejected due to multiple definitions
inline void bar () {} // ok because `inline` keyword is found
Beyond that it doesn't check if the function body is similar or not, because that is already parsed during earlier stage and linker doesn't parse the function body.
Having said above, now pay attention to this statement:
template functions are always inline by nature
Hence linker may not get a chance to reject them.
The safest way is to #include the read-only header into your specialized header and include that specialized header everywhere.
I don't know of a way to do this by analysis of the compiled binary, but you could build a graph of your program's #include relationships — there are tools that can do this, such as Doxygen — and use it to look for files that (directly or indirectly) include the library header but not the specialization header.
You'd need to examine each file to determine whether it actually uses the template in question, but at least you can narrow down the set of files that you have to examine.
I think you managed to deceive the compiler. But I should note that in my humble opinion you understand conception of templates in a wrong way, particularly you are trying to mix up template specialization with inheritance.
I mean, template specialization must not add data members to class, the only aims are to define types for function parameters and class fields. If you want to change algorithms, i.e. rewrite code, or add new date members to class, you should define derived class.
Concerning "several-step" separate compilation and template class in library, C++ reference said (http://www.cplusplus.com/doc/oldtutorial/templates/):
Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation (definition) of a template class or function must be in the same file as its declaration. That means that we cannot separate the interface in a separate header file, and that we must include both interface and implementation in any file that uses the templates.
Since no code is generated until a template is instantiated when required, compilers are prepared to allow the inclusion more than once of the same template file with both declarations and definitions in a project without generating linkage errors.

how linker decides which implementation use

Let's say we have the following files:
//foo.h
class Foo
{
public:
void foo()
{
//Great code here
}
};
//foo1.cpp
#include "foo.h"
void Foo1()
{
Foo f1;
f1.foo();
}
//foo2.cpp
#include "foo.h"
void Foo2()
{
Foo f2;
f2.foo();
}
When I compile them separated, they generate two objects: Foo1.o Foo2.o. When I link them together they link perfectly.
Now if I dump symbols table for both, the seems to implement Foo::foo function in the two compilation units.
_ZN3Foo3fooEv
Now, how does the linker distinguish which implementation to use?
Mats Petersson's answers entirely correct, but I'll spin this in my own words with different coverage....
When you compile C++ code, you compile it a translation unit at a time... each translation unit typically consists of one implementation file (e.g. .cpp/.cc or whatever you've chosen to name it) and the header files it includes, and the compiler produces one .o file. When the compiler sees your foo.h and the definition for Foo::foo(), it will consider it a nominally inline function because the function body appears inside the class. As such, the compiler may or may not actually inline the function at points of call - that decision will depend upon the size/complexity of the function and the compiler's heuristics and options. So, Foo::foo may still end up as separate out-of-line functions in the .os for both translation units.
Because the function's nominally inline, the compiler needs to make sure that the symbol is marked as a "weak symbol" (exact terminology may differ by OS/toolchain - this is implementation detail below the level of the C++ Standard) - see http://en.wikipedia.org/wiki/Weak_symbol
When objects are linked that have the same weak symbols in them, the code from one copy is kept and the other copies discarded. Consequently, both .o files may have the function (despite it being nominally inline due to definition in class), but the executable linked from the .os only has one copy.
Since the code in Foo::foo() is identical [if it's not, you are breaking the "one definition rule" - that is, one function should have ONE definition, no matter how many times it is actually defined].
So, the compiler/linker should be perfectly allowed to merge the two identical functions into one when completing your executable file.
Note however, that as it stands, Foo::foo() is declared as an inline function, which means that it's not "exported" to the outside world, and there should be no conflict.
If you were to "manually include" the class definition for Foo in both of your foo1.cpp and foo2.cpp, and make some subtle difference in the functions, you would find that the linker "picks" one of the functions, and discards the other one. Which it picks is not defined, and since the "one definition rule" has been broken, you are "outside the bounds of what you should do", so no point in complaining that the compiler "doesn't do the right thing". [Although you would have to make the function "non-inline" to make this a problem, and then you'd probably get a linker error for multiple definitions].
Both functions Foo1 and Foo2 are in their own respective translational units. When you include foo.h, both gets a copy of the entire Foo class. Thus, the linker uses each units respective copy.
Now if you implmented Foo::foo() inside it's own source file, then both Foo1 and Foo2 would use the same foo function during linking.

C++ include guard doesn't appear to work?

I have used include guards many times before, but never really understood how or why they work.
Why doesn't the following work?
#ifndef CAMERA_CLASS_HPP
#define CAMERA_CLASS_HPP
class camera_class
{
....
};
camera_class glcam = camera_class();
#endif // CAMERA_CLASS_HPP
The error is this: (You can probably guess what it's going to be from the title of this question!)
-------------- Build: Debug in System ---------------
Linking console executable: bin/Debug/System
/usr/bin/ld: error: obj/Debug/main.o: multiple definition of 'glcam'
/usr/bin/ld: obj/Debug/camera_class.o: previous definition here
/usr/bin/ld: error: obj/Debug/main.glfunc.o: multiple definition of 'glcam'
/usr/bin/ld: obj/Debug/camera_class.o: previous definition here
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings
Also, could someone please explain to me why a header guard works?
The header guard will prevent multiple inclusions in a single translation unit. The header can (and is) being included in multiple translation units:
// a.cpp:
#include "camera.hpp"
// b.cpp
#include "camera.hpp"
This will produce a a.obj and a b.obj, each containing a definition for glcam. When linked together to produce the final binary you get the multiple definition error.
You need to declare glcam in the header and define it exactly once in a .cpp file:
// camera.hpp
...
extern camera_class glcam;
// camera.cpp
#include "camera.hpp"
camera_class glcam;
Root Cause:
The header guard prevents inclusion of the same header multiple times in the same translation unit but not across different translation units. When you include the same header file in multiple translation units then,
A copy of glcam is indeed being created in every translation unit where you include the header.
C++ standard mandates that each symbol can be defined only once(One Definition Rule) and hence the linker issues you the error.
Solution:
Do not create glcam in the header file. Instead it should be created in such a way that it gets defined only once. The correct way to do this is by using the keyword extern.
It looks like you want to create a single glcam object that can be used in multiple places. I would do that by exposing a free function to return a static instance. This is similar to using extern, but I find it to be a little more explicit in its intent.
#ifndef CAMERA_CLASS_HPP
#define CAMERA_CLASS_HPP
class camera_class
{
....
};
camera_class& get_camera();
#endif // CAMERA_CLASS_HPP
// in the CPP
camera_class& get_camera()
{
static camera_class the_camera;
return the_camera;
}
This gives you the ability to use a single camera_class instance without relying on extern, but at the same time doesn't force you to use it as a singleton, as other areas of the code are free to create their own private instances as well.
This could be implemented as it is (a free-function) or as a static member function of the camera_class. I chose the former, based on some excellent advice from Scott Meyers:
If you're writing a function that can be implemented as either a
member or as a non-friend non-member, you should prefer to implement
it as a non-member function.
Source: http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197
Since you are including this file from several files, you are breaking the One Definition Rule:
In the entire program, an object or non-inline function cannot have
more than one definition
You should put the glcam definition in a source file, rather than in a header file, or instead declare it as extern, and provide a definition in some source file.
The include guard prevents multiple instances of the text in your header from appearing in one compilation unit (ie a single .cpp you're building which gets built into a .o)
It doesn't prevent multiple instances of that text from appearing in multiple compilation units.
So at link time, each compilation unit that includes this header has a
camera_class glcam = camera_class();
As a symbol. C++ can't decide when referring to "glcam" which single global definition you mean. The one from main.o or the one from camera_class.o?
It's working just fine, you're only getting one definition in each of your source files.
The problem is that you have multiple source files and the linker is finding multiple definitions.
In the header file you should put:
extern camera_class glcam;
And then in one and only one source file put what you used to have in the header:
camera_class glcam = camera_class();
At this point you'll need to be aware of initialization order problems. Don't try to use glcam from any static objects.

C++ including a ".h" file, function duplication confusion

I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).
Basically, my program was structured as follows:
The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).
Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc). CalledByCurrent.h contains a class definition.
There was a non-class function defined in CalledByCurrent.cc called thisFunction(). thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function). In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc. However, when I did this, I got an error saying that the function was duplicated. Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?
Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc. However, when I did this, I found that Current.cc did not know what function I was talking about. What the heck? I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem. Could you help me understand this behavior? Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?
p.s - I apologize for how confusing this post is. Please let me know if there's anything I can clear up.
You are getting multiple definitions from the linker - it sees two functions with the same name and complains. For example:
// a.cpp
void f() {}
// b.cpp
void f() {}
then
g++ a.cpp b.cpp
gives:
C:\Users\neilb\Temp\ccZU9pkv.o:b.cpp:(.text+0x0): multiple definition of `f()'
The way round this is to either put the definition in only one .cpp file, or to declare one or both of the functions as static:
// b.cpp
static void f() {}
You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.
EDIT
You can use the function in the other .cpp file by using extern keyword. See this example:
//Test.cpp
void myfunc()
{
}
//Main.cpp
extern void myfunc();
int main()
{
myfunc();
}
It will call myfunc() defined in test.cpp.
The header file inclusion mechanism should be tolerant to duplicate header file inclusions.
That's because whenever you simply declare a function it's considered in extern (global) scope (whether you declare it in a header file or not). Linker will have multiple implementation for the same function signature.
If those functions are truely helper functions then, declare them as;
static void thisFunction();
Other way, if you are using the same function as helper then, simply declare it in a common header file, say:
//CalledByCurrent.h (is included in both .cc files)
void thisFunction();
And implement thisFunction() in either of the .cc files. This should solve the problem properly.
Here are some ideas:
You didn't put a header include guard in your header file. If it's being included twice, you might get this sort of error.
The function's prototype (at the top) doesn't match its signature 100%.
You put the body of the function in the header file.
You have two functions of the same signature in two different source files, but they aren't marked static.
If you are using gcc (you didn't say what compiler you're using), you can use the -E switch to view the preprocessor output. This includes expanding all #defines and including all #includes.
Each time something is expanded, it tells you what file and line it was in. Using this you can see where thisFunction() is defined.
There are 2 distinct errors coming from 2 different phases of the build.
In the first case where you have a duplicate, the COMPILER is happy, but the LINKER is complaining because when it picks up all the function definitions across the different source files it notices 2 are named the same. As the other answers state, you can use the static keyword or use a common definition.
In the second case where you see your function not declared in this scope, its because the COMPILER is complaining because each file needs to know about what functions it can use.
Compiling happens before Linking, so the COMPILER cannot know ahead of time whether or not the LINKER will find a matching function, thats why you use declarations to notify the COMPILER that a definition will be found by the LINKER later on.
As you can see, your 2 errors are not contradictory, they are the result of 2 separate processes in the build that have a particular order.