I included this header into one of my own: http://codepad.org/lgJ6KM6b
When I compiled I started getting errors like this:
CMakeFiles/bin.dir/SoundProjection.cc.o: In function `Gnuplot::reset_plot()':
/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/new:105: multiple definition of `Gnuplot::reset_plot()'
CMakeFiles/bin.dir/main.cc.o:project/gnuplot-cpp/gnuplot_i.hpp:962: first defined here
CMakeFiles/bin.dir/SoundProjection.cc.o: In function `Gnuplot::set_smooth(std::basic_string, std::allocator > const&)':
project/gnuplot-cpp/gnuplot_i.hpp:1041: multiple definition of `Gnuplot::set_smooth(std::basic_string, std::allocator > const&)'
CMakeFiles/bin.dir/main.cc.o:project/gnuplot-cpp/gnuplot_i.hpp:1041: first defined here
CMakeFiles/bin.dir/SoundProjection.cc.o:/usr/include/eigen2/Eigen/src/Core/arch/SSE/PacketMath.h:41: multiple definition of `Gnuplot::m_sGNUPlotFileName'
I know it's hard to see in this mess, but look at where the redefinitions are taking place. They take place in files like /usr/lib/gcc/x86_64-pc-linux-gnu/4.3.4/include/g++-v4/new:105. How is the new operator getting information about a gnuplot header? I can't even edit that file. How could that ever even be possible? I'm not even sure how to start debugging this. I hope I've provided enough information. I wasn't able to reproduce this in a small project. I mostly just looking for tips on how to find out why this is happening, and how to track it down.
Thanks.
You're obviously violating the "one definition rule". You have lots of definitions in your header file. Some of them are classes or class templates (which is fine), some of them are inline functions or function templates (which is also fine) and some of them are "normal" functions and static members of non-templates (which is not fine).
class foo; // declaration of foo
class foo { // definition of foo
static int x; // declaration of foo::x
};
int foo::x; // definition of foo::x
void bar(); // declaration
void bar() {} // definition
The one definition rule says that your program shall contain at most one definition of an entity. The exceptions are classes, inline functions, function templates, static members of class templates (I probably forgot something). For those entities multiple definitions may exist as long as no two definitions of the same entity are in the same translation unit. So, including this header file into more than one translation unit leads to multiple definitions.
Looks like you include conflicting headers. Try to check your include paths. They usually are defined in -I directive (at least in gcc) or in an environment variable.
Reading compiler errors usually helps. You should learn to understand what the compiler is telling you. The fact that it is complaining about a symbol being redefine is saying that you are breaking the One Definition Rule. Then it even tells you what the symbols are:
class GnuPlot {
//...
GnuPlot& reset_plot(); // <-- declaration
//...
};
//...
Gnuplot& Gnuplot::reset_plot() { // <-- Definition
nplots = 0;
return *this;
}
You can declare a symbol as many times as you wish within a program, but you can only define it once (unless it is inlined). In this case the reset_plot is compiled and defined in all translation units that include the header, violating the One Definition Rule.
The simplest way out of it is declaring it inline, so that it can appear in more than one compilation unit and let the linker remove the redundant copies (if any) later on.
A little more problematic are the static members that must be declared within the class and defined (only once) in a translation unit. For that you can either create a .cpp file to define those variables (and any function/method that you don't need inlined in the header).
Related
I have read existing answers on the two meanings of inline, but I am still confused.
Let's assume we have the following header file:
// myclass.h
#ifndef INCLUDED_MYCLASS
#define INCLUDED_MYCLASS
class MyClass
{
public:
void foo(); // declaration
};
inline void MyClass::foo()
{
// definition
}
#endif
Why does void foo() which is defined outside the class in the file, have to be explicitly defined with inline?
It's because you defined MyClass::foo in a header file. Or a bit more abstract, that definition will be present in multiple translation units (every .cpp file that includes the header).
Having more than one definition of a variable/function in a program is a violation of the one definition rule, which requires that there must be only one definition in a single program of every variable/function.
Note that header guards do not protect against this, as they only protect if you include the same header multiple times in the same file.
Marking the function definition as inline though means that the definition will always be the same across multiple translation units.1.
In practice, this means that the linker will just use the first definition of MyClass::foo and use that everywhere, while ignoring the rest,
1: If this is not the case your program is ill-formed with no diagnostics required whatsoever.
If you put MyClass::foo() in a header file and fail to declare it inline then the compiler will generate a function body for every compilation unit that #includes the header and these will clash at link time. The usual error thrown by the linker is something along the lines of Multiple definition of symbol MyClass::foo() or somesuch. Declaring the function inline avoids this, and the compiler and linker have to be in cahoots about it.
As you mention in your comment, the inline keyword also acts a hint to the compiler that you'd like the function to be actually inlined, because (presumably) you call it often and care more about speed than code size. The compiler is not required to honour this request though, so it might generate one or more function bodies (in different compilation units) which is why the linker has to know that they are actually all the same and that it only needs to keep one of them (any one will do). If it didn't know they were all the same then it wouldn't know what to do, which is why the 'classical' behaviour has always been to throw an error.
Given that the compilers these days often inline small functions anyway, most compilers also have some kind of noinline keyword but that is not part of the standard.
More about inline at cppreference.
I have this little piece of code :
File modA.h
#ifndef MODA
#define MODA
class CAdd {
public:
CAdd(int a, int b) : result_(a + b) { }
int getResult() const { return result_; }
private:
int result_;
};
/*
int add(int a, int b) {
return a + b;
}
*/
#end
File calc.cpp
#include "modA.h"
void doSomeCalc() {
//int r = add(1, 2);
int r = CAdd(1, 2).getResult();
}
File main.cpp
#include "modA.h"
int main() {
//int r = add(1, 2);
int r = CAdd(1, 2).getResult();
return 0;
}
If I understand well, we can't define a function in a header file and use it in different unit translations (unless the function is declared static). The macro MODA wouldn't be defined in each unit translation and thus the body guard wouldn't prevent the header from being copied in place of every #include "modA.h". This would cause the function to be defined at different places and the linker would complain about it. Is it correct ?
But then why is it possible to do so with a class and also with methods of a class. Why doesn't the linker complain about it ?
Isn't it a redefinition of a class ?
Thank you
When member functions are defined in the body of the class definition, they are inline by default. If you qualify the non-member functions inline in the .h file, it will work fine.
Without the inline qualifier, non-member functions defined in .h files are compiled in every .cpp file that the .h file is included in. That violates the following rule from the standard:
3.2 One definition rule
3 Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; ...
You will get the same error if you define member functions outside the body of the class definition in a .h file and did not add the inline qualifier explicitly.
Multiple translation units might need the definition of the class at compile time since it is not possible to know, for example, the types of members of the class (or even whether they exist) unless the definition of the class is available. (Therefore, you must be allowed to define a class in multiple translation units.) On the other hand, a translation unit only needs the declaration of a function because as long as it knows how to call the function, the compiler can leave the job of inserting the actual address of the function to the linker.
But this comes at a price: if a class is defined multiple times in a program, all the definitions must be identical, and if they're not, then you may get strange linker errors, or if the program links, it will probably segfault.
For functions you don't have this problem. If the function is defined multiple times, the linker will let you know. This is good, because it avoids accidentally defining multiple functions with the same name and signature in a given program. If you want to override this, you can declare the function inline. Then the same rule as that for classes applies: the function has to be defined in each translation unit in which it's used in a certain way (odr-used, to be precise) and all the definitions must be identical.
If a function is defined within a class definition, there's a special rule that it's implicitly inline. If this were not the case, then it would make it impossible to have multiple definitions of a class as long as there's at least one function defined in the class definition unless you went to the trouble of marking all such functions inline.
” If I understand well, we can't define a function in a header file and use it in different unit translations (unless the function is declared static)
That's incorrect. You can, and in the presented code CAdd::getResult is one such function.
In order to support general use of a header in multiple translation units, which gives multiple competing definitions of the function, it needs to be inline. A function defined in the class definition, like getResult, is automatically inline. A function defined outside the class definition needs to be explicitly declared inline.
In practical terms the inline specifier tells the linker to just arbitrarily select one of the definitions, if there are several.
There is unfortunately no simple syntax to do the same for data. That is, data can't just be declared as inline. However, there is an exemption for static data members of class templates, and also an inline function with extern linkage can contain static local variables, and so compilers are required to support effectively the same mechanism also for data.
An inline function has extern linkage by default. Since inline also serves as an optimization hint it's possible to have an inline static function. For the case of the default extern linkage, be aware that the standard then requires the function to be defined, identically, in every translation unit where it's used.
The part of the standard dealing with this is called the One Definition Rule, usually abbreviated as the ODR.
In C++11 the ODR is §3.2 “One definition rule”. Specifically, C++11 §3.2/3 specifies the requirement about definitions of an inline function in every relevant translation unit. This requirement is however repeated in C+11 §7.1.2/4 about “Function specifiers”.
I have read many posts before posting this one, I couldnt find a solution because non of them (those I read) were on data structures.
I have two data structures (If it matter, a Heap and a UF).
Both of them are implemented in the .h file.
I'm getting the "Multiple definition of.." "First defined here" errors only on member functions implemented outside of the class (such as int UnionFind::Find(int i) )
It happens for the c'tors and d'tors also, but when I implement them in the class itself, it disappear.
I really have no clue why it is happening.
I have followed the includes in all of my files and there are no double includes or loops.
I'm also using an AVL tree, and it does not happen there, everything there is implemented in the .h file outside of the class.
These are the errors im getting :
/tmp/ccp8fP73.o: In function `UnionFind::Find(int)':
main.cpp:(.text+0x0): multiple definition of `UnionFind::Find(int)'
/tmp/ccVxSiPy.o:Elections.cpp:(.text+0x0): first defined here
/tmp/ccp8fP73.o: In function `UnionFind::Union(int, int)':
main.cpp:(.text+0x108): multiple definition of `UnionFind::Union(int, int)'
/tmp/ccVxSiPy.o:Elections.cpp:(.text+0x108): first defined here
If you need more info, please tell me.
Thank you
If I understand you correctly, you are doing things like this:
// C.h
class C
{
void f(); // declaration of f; ok to include in many modules
};
// definition of f; must not exist in more than one module
void C::f()
{
}
That doesn't work because the definition of f() will wind up in every module that includes C.h, leading to exactly the linker error you describe. You can fix this by either marking f() as inline, or by moving the definition of f() to a separate cpp file.
There is one special case where this is allowed, and that's when f() is a template (either directly or because C is a template). In that case, the definition must be in the header so the compiler can know how to instantiate it for whatever type(s) you specify. This does make life difficult for the linker since you can and often do end up with the sorts of redundant definitions that would normally be errors (e.g if you use f<int>() in more than one module). Special behavior is needed to handle this.
Incidentally, the reason things work when you move the function bodies inside the class definition is because that has the effect of making them implicitly inline.
If you want to create your templates manually..
//1. include the template code..
#include <template/list.tmpl.c>
// 2. instantiate the instances that use it..
#include "/c/viewer/src/ViewObject.h"
#include "/c/viewer/src/WindowAdaptor.h"
template class List<ViewObject>;
template class List<WindowAdaptor>;
When I have the following code in A.cpp and B.cpp there is no warning or error generated, but Initializer::Initializer() in B.cpp gets called twice while the one in A.cpp doesn't get called.
static int x = 0;
struct Initializer
{
Initializer()
{
x = 10;
}
};
static Initializer init;
Since this is breaking the one definition rule and causing undefined behavior I think this is perfectly normal. However, when I move the constructor definition outside of the class declaration in either or both files, like this:
static int x = 0;
struct Initializer
{
Initializer();
};
Initializer::Initializer()
{
x = 10;
}
static Initializer init;
The linker suddenly becomes smart enough to error and say one or more multiply defined symbols found. What changed here and why did it matter? I would have thought the linker should always be able to detect ODR breakage - what are the cases when it can't?
Someone correct me if I'm wrong, but my theory is that when you have templated code (where the definitions are always in headers) you end up with duplicated definitions in many compilation units. They happen to all be identical, so it doesn't matter if the linker just chooses one and orphans the others, but it can't error that there are multiple definitions or templates wouldn't work.
Your second example has an obvious and easy to diagnose violation of the one definition rule. It has two definitions of a non-inline function with external linkage. This is easy for the linker to diagnose as the violation is obvious from the names of the functions contained in the object files that it is linking.
Your first example breaks the one definition rule in a much subtler way. Because functions defined in a class body are implicitly declared inline you have to examine the function bodies to determine that the one definition rule has been violated.
For this reason alone I am not surprised that your implementation fails to spot the violation (I didn't the first time around). Obviously the violation is impossible for the compiler to spot when looking at one source file in isolation but it may be that the information to detect the violation and link time is not actually present the object files that are passed to the linker. It is certainly beyond the scope of what I'd expect a linker to find.
The multiply defined symbol error occurs when multiple translation units each have the same name signature for an item with external linkage, except if they are inlined functions or methods.
Inlined functions are typically not subject to ODR at compile time. If they were, inlined implementations of methods would break everywhere. However, the ODR is applied retroactively during link time, in that one inline function is chosen. So, inline functions with the same signature are expected to behave identically. Your inline constructors violate that expectation.
If instead you had declared a template in a header file, like this:
#ifndef I_HH
#define I_HH
tempalte <typename T>
struct Initializer {
Initializer () { x = 10; }
};
#endif
and used this to be included in both A.cpp and B.cpp, and in each you created a static instance:
static int x;
#include "i.hh"
static Initializer<int> init;
I believe the compiler should complain about an improperly formed template (g++ did anyway), which is as good as detecting a violation of ODR (that the constructors would behave differently in different contexts).
if you have the implement of function within the class defination, the function is inlined which don't required to linked. So there has no error.
There must has one definition, but doesn't matter it is included by different cpp file. for example, you defined one class in a header file but include the header file in different cpp files.
Okay, up until now, I thought that functions defined in header files are treated like inline functions, just like template stuff, defined once, and all that.
I also use inclusion guards, yet I still got linker errors of multiple defined objects, and I know that is because of all those different units duplicating stuff the linker tries to pick out which item is the right one.
I also know that inline is merely a suggestion, and might not even get used by the compiler, etc.
Yet I have to explicitly define all those small functions in that little header only toolset I wrote.
Even if the functions were huge, I'd have to declare them inline, and the compiler would still possibly disregard the hint.
Yet I have to define them so anyway.
Example:
#ifndef texture_math_h__
#define texture_math_h__
float TexcoordToPixel(float coord, float dimension)
{
return coord * dimension;
}
float PixelToTexcoord(float pixel, float dimension)
{
return pixel / dimension;
}
float RecalcTexcoord(float coord,float oldDimension, float newDimension)
{
return PixelToTexcoord(TexcoordToPixel(coord,oldDimension),newDimension);
}
#endif // texture_math_h__
Errors are , blabla already defined in xxx.obj, for each unit that includes the file
When I declare all of those inline, it links correctly.
What's the reason for that? It's not a huge problem, and heck, optimizations probably inline stuff found in cpp, too, right?
I'm just curious about the why here, hope it's not too much of a duplicate and thank you for your time.
Inclusion guards only guard against the code being included twice in the same translation unit. So if you have multiple files that include the same header, the code is included multiple times. Functions defined in a header are not inline by default, so this will give you linker errors - you need to define those function with the inline keyword, unless they are member functions of a class.
Also, note that names that contain double-underscores are reserved for the purposes of the C++ implementation - you are not allowed to create such names in your own code.
Member functions are potencially inlined - you can't force inlining! - if (a) they are defined inside the class or if (b) you use the inline-clause in the definition. Note if you are using the inline-clause you shouldn't define the function in the header - the only exception would be templates as these are "special".
As you just updated the question:
Every user of this header will have a definition of the functions -> multiple defintions. You need to separate definition and declaration!
It's all about the one definition rule. This states that you can only have one definition for each non-inline function (along with various other types of entity) in a C++ program across all the translation units that you link in to make the program.
Marking a function inline enables an exception to the usual one definition rule. It states (paraphrased) that you can have one definition of an inline function per translation unit provided that all the definitions match and that a definition is provided in each translation in which the inline function is used.
Include guards will prevent you from accidentally providing more than one definition per translation unit by including the header file containing the definitions multiple times.
To satisfy the one definition rule for a non-inline function you would still have to ensure that there is only one translation unit containing the function definitions. The usualy way to do this is by only declaring the functions in the header file and having a single source file containing the definitions.