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
Related
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 want to include implementation of a function inside an .h file.
I know I would rather separate declaration and implementation to .h and .c file accordingly, this is not a part of my question.
When I implement the function inside the class, I receive no errors:
class Foo
{
public:
// Class constructor
Foo() { }
};
When I implement the function outside the class (still in the .h file):
class Foo
{
public:
// Class constructor
Foo();
};
Foo::Foo()
{
}
I receive the following error:
multiple definition of Foo:Foo()
Can someone explain me the logic behind this? Thanks.
This is because when you define the function in the class definition, the method is treated as an inline function. Which can be included in multiple source files, be compiled and linked together and still have the linker not complain about multiple definitions.
But when you define the constructor outside the class, #include it in multiple source files, compile them together and then link them. You get multiple definitions for the same function.
Remember that #includeing a file is essentially a copy paste of that file into the file that #includes it. So every time that file is included, you get a definition for the function in that source file. And then when you compile and link multiple such sources together you get multiple definitions for the same non-inline function.
For more see on inline, see http://en.cppreference.com/w/cpp/language/inline. The examples section has a good chunk of code that should help.
You can also explicitly mark the definition outside the class to be inline like #StoryTeller correctly noted.
Mark it inline
class Foo
{
public:
// Class constructor
inline Foo();
};
inline Foo::Foo()
{
}
Like Curious said, an in-class definition is implicitly inline. But if you define it outside the class, in a header, you must add the specifier explicitly.
The inline specifier is very important for correct linkage in cases like this. It allows the same function to exist in multiple translation units, so long as it's the exact same function body. A case that often occurs with functions defined in a header file.
This question already has answers here:
C++ inlining class methods causes undefined reference
(3 answers)
Closed 1 year ago.
I have some member functions in a class. When I use the inline specifier, the compiler complains of undefined reference.
I have tried:
Using 'inline' to precede the function definition in the class header file only.
Using 'inline' to precede the function declaration in the class .cpp (where the member functions are specified) file only.
Doing both of the above at the same time.
Obviously, one of these ways is the correct thing to do, and the others are not correct. However trying each option did not get me a program which compiled.
Here is what I am trying to do:
.hpp file:
class A{
void func();
}
.cpp file:
... include ...
inline void A::func()
{
...
}
Or maybe 'inline' goes elsewhere. I have tried all possible combinations I could think of, as I explained above. (Now watch someone tell me I need it AFTER the function name and arguments, like the keyword 'const'.)
Anyone any ideas on what I am doing wrong? I tried googling what the correct answer might be, but no luck. Are 'inline' functions inside a class even a thing?
Inline functions have to be defined in header files. The definition (the body) of the function has to be visible in all translation units that attempt to use that function. You can define it directly inside the class. Or you can define it as in your code, i.e. outside of the class. But it has to be in header file, not in .cpp file.
Attempting to define an inline function in .cpp file will make it usable in that .cpp file only. Trying to use it in other .cpp files will lead to linker errors (i.e. "undefined reference" errors).
Putting inline anything inside the CPP file can only possibly inline the function inside that file. If you want to encourage the compiler to inline the function, you need to forget about the CPP file. Instead, do this in the hpp file:
class A{
inline void func();
};
void A::func() {...}
NB a few points:
Putting inline doesn't mean your function will be inlined. It's a hint to the compiler.
You need optimization (-O3 in gcc) to even have a chance at it being inlined
If you define the function inside the class, it implicitly has the inline keyword on:
class A{
inline void func() {
...
}
};
is the same as the above where it was declared inline in the class and the definition was outside.
There are ways to force GCC to inline your code using function attributes, but I will not describe them because it is rarely a good idea to use them. GCC should do the "best" thing regarding inlining for each function. Forcing it to do something else will almost always result in worse performance.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can templates only be implemented in the header file?
I've been trying around with C++ recently.
At the moment I'm trying to program something I'm sure everone has done at least once: A simple LinkedList class.
The code is done, but I'm somehow failing to compile it. I've been googling and it seems like I'm linking the object files wrong. That's what my code basically looks like:
test.cpp
#include "linkedlist.h"
int main()
{
LinkedList<int> list;
// do something
}
linkedlist.h
template <typename T>
class LinkedList
{
// a lot of function and variable definitions
}
Then there's a .cpp file called linkedlist.cpp which contains all the actual code of the LinkerList class. When trying to compile test.cpp using the following command:
g++ ..\src\test.cpp
I'm getting told that there's an undefined reference to 'LinkedList::LinkedList()'. So I've been thinking that it's being linked wrong as there's more than one .cpp file, so I tried it like this:
g++ -c -Wall -O2 ..\src\test.cpp
g++ -c -Wall -O2 ..\src\linkedlist.cpp
g++ -s test.o linkedlist.o
However, this doesn't change anything. The error messages stay the same.
I've been trying to find some information on the internet, however, it didn't really work out.
You're creating a class template, which has the important caveat that all variable definitions must be placed in the header file so that they're accessible to all translation units during compilation.
The reason is the way that templates work. During compilation, the compiler instantiates template classes based on your class template definition. It isn't enough for it to have access to only the declarations or signatures: it needs to have the entire definition available.
Move all of your method definitions out of the .cpp file and into the .h file, and everything should be fine (assuming that you have, in fact, provided a definition for the default constructor!).
Alternatively, you might be able to get around this by explicitly telling your compiler to instantiate the appropriate template class using something like template class LinkedList<int>, but this really isn't necessary in such a simple case. The primary advantage of this over including all of the definitions in the header file is that it potentially reduces code bloat and speeds up compilation. But it might not be necessary at all, as compilers have gotten a lot smarter at applying appropriate optimizations.
You have split up your class LinkedList and put the declaration in a header and the defintion in a source-file. This does not work for a template. Both have to be in the header.
Template class is like a definition of a rule by which to construct an actual class. The actual classes are created (instantiated) by the compiler wherever there is instantiation of template class. For this reason all the code of template class must be visible to a compiler at that point, and that's why you have to write all the template functions and methods in a header files - because you only include headers to cpp files, only headers are visible to a compiler at that point. You don't include cpp files to another cpp files, and you should never do that.
Correct me if my understanding is wrong.
P. S.
Does C++11 address this issue?
Since LinkedList is a class template, the definitions of its member functions ought to go in a header.
(They don't have to be, strictly speaking, but this is the easiest way to get around the complexities of template instantiation without going totally off-piste with inclusion conventions.)
Oh, and you'd need to take your second build approach anyway; you should link together all .cpp files, or use the -c switch to compile one at a time then link the results together later.
there's an undefined reference to 'LinkedList::LinkedList()'
Have you checked to see if your LinkedList class has a constructor?
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.
I currently have a program where my main code is in a file main.cpp.
Main.cpp includes a header file "class.h" that declares a class that is used within main.cpp.
Also in main.cpp I have function declarations that declare the functions I use within main.cpp.
The code for these functions is in a separate .cpp file fucntions.cpp.
Like main.cpp, functions.cpp also includes class.h as the class type is used within the functions.
class.h contains the class declaration only.
The implementation code for class.h is in a separate .cpp file classimplementation.cpp.
It all works fine until I try to make the class in class.h a template class.
Then I get linking problems. Research and testing has shown me that this is because the definition of the template class functions needs to reside in class.h with the declaration.
I therefore took the required code out of classimplementations.cpp and put it into class.h.
This did solve my original linking issues but instead I get more linking errors that seem to be telling me I am trying to redefine the functions that I moved to into class.h.
This I think is because class.h is being called by main.cpp and again by functions.cpp.
Therefore the functions in class.h are being defined twice:
Error 41 error LNK2005: "public: __thiscall RecordPocket::RecordPocket(int)" (??0?$RecordPocket#VT####QAE#H#Z) already defined in classimplementation.obj functions.obj
I know that class implementation code should really be kept out of include files but due to the template class limitation of having to keep the class functions local I appear (in my novice mind) to have no choice.
Has anyone been in this scenario and can offer any advice.
I have tried surrounding the functions I moved from classimplementation.cpp to class.h with the standard ifndef CLASSIMP, #define CLASSIMP code and PRAGMA ONCE but neither make any difference.
If all else fails I will move the functions from functions.cpp into main.cpp so that class.h gets called just the once but I’d rather find out what I’m doing wrong as I’m sure it will happen again.
You could keep the template functions inside the template<> class what{/HERE/};
template<typename T>
class MyTempClass{
void myFunctions{
// code here
}
}
EDITED: I removed the code corrected by Glen
I think your problem is revolves around these issues. As you have implied any template function definition (i.e. template function of member function of a template class) needs to be fully expressed in the .h file because when the compiler finds a specific instance of the template it needs to build the function.
You figured this out and moved some implementation into your class.h file. Now if the linker find a MyFunction() in more than one module then is just discards one of them a no linker error is reported.
However you can't define the same non-template function in two different modules as this generates the error you are getting above. So I suspect you also moved some non-template functionality into the .h file; thus including it in two separate obj files and generating the linker error. This theory is support by your quoted error message as I note __thiscall RecordPocket::RecordPocket(int) does not appear to be template.