I am making libraries, to use in multiple games so I don't have to duplicate code. In this example, my main program is main.cpp and the other two files are my libraries. Everything is linked correctly.
When all my functions in Common Functions Library.h have static in front, I get the error: static function 'std::string common::joinAll(std::vector<std::string,std::allocator<_Ty>>)' declared but not defined (Error C2129) from main.cpp (even though the functions are in the Common Functions Library.h/.cpp), and it says the line number is one more than there is in the whole program which is very strange.
So, to fix this, I found people online saying I need to replace static with inline, so I tried again and got this error: cannot open file 'Common Functions Library.lib' (Error LNK1104)
Then I tried setting all the functions back to static, and then commented out #include "Cubes Library.h" in main.cpp, which didn't give me the other errors anymore, but instead things related to the cubes library (obviously). However, this stopped on line 65, after where the functions which caused the errors saying they weren't defined. I have no clue what is going wrong, but thanks for any help :)
Code:
main.cpp
#include "Common Functions Library.h"
#include "Cubes Library.h"
// Using functions from `Common Functions Library`
Common Functions Library.cpp (Part of a DLL)
#include "Common Functions Library.h"
namespace common
{
// Functions
}
Cubes Library.cpp (Part of a DLL)
#include "Cubes Library.h"
#include "Common Functions Library.h"
If you put inline in front of all functions and define in header, there is no need for .cpp file and hence no need for .lib.
I also see namespace common in your Common Functions Library.h. So don't forget to put using namespace common; in your main.cpp or prefix common:: before all usage of class in main.cpp.
Related
I have this simple code in C++
#include <something.h>
#include <something2.h>
int main()
{
my_function();
return 0;
}
function with name my_function is defined in something.h and also in something2.h How to choose whichone I want to use without editting included files?
One solution is to use
namespace something_one
{
#include <something.h>
}
namespace something_two
{
#include <something2.h>
}
This works well if all the code is in the headers.
Otherwise you have to resort to #defines, stub functions implemented in carefully crafted compilation units, or a robust conversation with the global namespace polluter.
Assuming that actual definition resides in something.cpp (or .c) and something2.cpp (or .c),
Link only one of something.o or something2.o at the time of creating main application executable, depending upon from which file you want function to get executed.
With linking the correct file, you do not need to change any source code.
you might have to declare them as extern "C" at the point declaration and definition if you are compiling it as c++ files with g++ or gcc -std=c++0x or gcc -std=c++11.
I'm trying to write a simple application allowing the user to perform a series of symbolic manipulations on a set of linear equations and am using the "Symbolicc++" library (more specifically, the latest version 3.35) for this purpose.
Since I don't have much experience with C++ and have never actually used a third-party library before, it's quite possible that I simply don't know how to properly use a library and am making some stupid mistake.
The problem is that I get a lot of multiple definition errors when I try to compile (and link) any program consisting of more than one file that includes the library's main header; the errors refer to functions and classes that are defined in the library's files (not mine).
A very simplistic example: suppose we have the files main.cpp, head.h and head.cpp. The contents is as follows:
main.cpp
------------------
#include <iostream>
#include "head.h"
int main()
{
return 0;
}
head.h
------------------
#ifndef SOMETHING
#define SOMETHING
#include "symbolicc++.h"
#endif
head.cpp
------------------
#include "head.h"
//nothing
Of course, the files in the real program contain a lot more, but even with just this, trying to build the program with, e.g.:
g++ -I /path to library's header files/ main.cpp head.cpp
yields hundreds of error message along the likes of:
/tmp/ccYNzlEF.o: In function `Cloning::Cloning()':
head.cpp:(.text+0x0): multiple definition of `Cloning::Cloning()'
/tmp/ccNWUnnC.o:main.cpp:(.text+0x0): first defined here
where, e.g., Cloning::Cloning() is declared in cloning.h, which is one of the library's header files.
A program containing only a single file including symbolicc++.h works just fine.
I also tried building this project on Visual Studio 2012 and got a similar result.
Unfortunately, I wasn't able to find any information about this problem, as virtually all the materials I found concerned errors in header files created by the user (as opposed to libraries created by someone else), so any help would be appreciated.
This library seems seriously broken. The way it is designed, you cannot include "symbolicc++.h" multiple times without violating the one-definition rule.
For example, let's have a look at cloning.h. It defines a Cloning class with a default constructor declaration:
class Cloning
{
private: int refcount;
void (*free_p)(Cloning*);
// ...
public: Cloning();
// ...
};
Later on, within the header file, it also defines that constructor:
Cloning::Cloning() : refcount(0), free_p(0) {}
That's it. Every one of your *.cpp files which directly or indirectly includes cloning.h will be exposed to the definition of the same function. The linker notices the multiple definitions and gives up.
Try to modify cloning.h. Remove the constructor definition line above and place the constructor definition into the class definition, making it an inline function:
// just to see what's going on...
class Cloning
{
private: int refcount;
void (*free_p)(Cloning*);
// ...
public: Cloning() : refcount(0), free_p(0) {};
// ...
};
This will fix the error for Cloning::Cloning. But that's just to shed more light on the issue; I don't advise you to do this. It would be the library authors' job to fix their code.
Further recommended reading: Why include guards do not prevent multiple function definitions?
Here is a way for you to reproduce the same problem with a few lines of your own code:
head.h:
#ifndef SOMETHING
#define SOMETHING
struct Example
{
Example(); // constructor declaration
};
Example::Example() // constructor definition
{
}
#endif
head.cpp:
#include "head.h"
//nothing
main.cpp:
#include "head.h"
int main()
{
}
Example linker error (taken from Visual C++ 2013):
1>main.obj : error LNK2005: "public: __thiscall Example::Example(void)" (??0Example##QAE#XZ) already defined in head.obj
1>[...] fatal error LNK1169: one or more multiply defined symbols found
If you absolutely must use this library, you'll have to build your own safe wrapper around it. But frankly, just don't. I'm sure there are numerous other libraries that solve the same problems and that can actually be used according to C++ language rules and conventions.
I'm trying to deal with this problem for some time and I can't seem to find the solution. I'm getting error:
one or more multiply defined symbols found
I faced this error while dealing with something more complicated, but even simple examples like this one don't work for me. Here is my main.cpp:
#include "defs.cpp"
int main()
{
string a = "A";
printIt(a);
}
, and here is my defs.cpp:
#include "header.h"
void printIt(string a)
{
cout << a;
}
, and this is my header.h:
#include <string>
#include <iostream>
using namespace std;
void printIt(string a);
I guess this is something trivial, but please don't rage if you think this is duplicate, because I'm a beginner and I didn't understand more complicated examples. Some help would be appreciated.
When you see #include "defs.cpp" you need to get very suspicious: cpp files are not meant to be included; only header files are designed for that.
Instead of including a cpp file, write a header for it. It appears that you have a suitable header already - your header.h, which contains the forward declaration of printIt:
void printIt(string a);
Now replace #include defs.cpp with #include "header.h", and compile your code. This should fix the problem.
Compiling this depends on the system where you are trying it out. On UNIX-like systems, you would write
g++ defs.cpp main.cpp
./a.out
You should not #include a CPP file. Only include header files containing the function prototype definitions. If no such header file exists, put the function prototype in your program (for eg. in file where main is written).
In your case, you are including (directly/indirectly) the CPP file which is having the definition of the function. Since same definition is compiled through CPP files, compiler is putting them into .OBJ file (known as intermediate or object files). The linker finally attempts to combine these Object files, and says some function (symbol) is multiply defined.
In main.cpp you are including defs.cpp which includes a definition of printIt. So the translation unit corresponding to main.cpp defines printIt.
However, you are also compiling defs.cpp which defines printIt. defs.cpps corresponding translation unit thus defines printIt too.
Combining both into one program would lead to multiple (yet equivalent) definitions of this function which is forbidden by the ODR. Remove the #include directive and your program should link correctly.
This is because you are including:-
#include "defs.cpp"
and due to this there are multiple definitions of method printIt.
These are some basic rules:-
1) You must always include only header files in your source files. Even then you have to make sure header files are included only once because if it is included more than once then there could again be problem of multiple definition.To protect against that your header files should contain header gaurds.
2) C++ always adheres with single definition rule. However , you can have as many declaratons as possible as long as all declarations are consistent.
I am using an open source library, which provides a .hpp-file with several static functions defined that looks like the code below.
When I include this file twice in my project I always get a linker error that complains about duplicate symbols. I am well aware of the fact that the functions are being defined twice, but I do not know how to resolve this. I have tried marking the functions extern or inline without success.
What is the best way to resolve this?
#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#include <algorithm>
#include <cmath>
#include <iterator>
#include <vector>
#include <limits>
#include <iostream>
#include "openMVG/robust_estimation/rand_sampling.hpp"
namespace openMVG {
namespace robust{
static double logcombi(size_t k, size_t n)
{...}
...
Edit: I forgot to say that there are also template functions, which means that I cannot use .h and .cpp files. So that is why they used .hpp files. On this page ( http://www.cplusplus.com/doc/tutorial/templates/ ) on the bottom it says that linkers should not produce errors in this case. I am using Xcode as an IDE with standard settings. Apparently there is something wrong here. The linker error looks like this:
duplicate symbol __ZN7openMVG6robust13UniformSampleEmmPSt6vectorImSaImEE in:
/Users/chris/Library/Developer/Xcode/DerivedData/SfM_OpenMVG-dgkssozpvorbpphdefdpurfpdaqv/Build/Intermediates/SfM_OpenMVG.build/Debug/SfM_incremental_unified.build/Objects-normal/x86_64/SfMIncrementalEngine.o
/Users/chris/Library/Developer/Xcode/DerivedData/SfM_OpenMVG-dgkssozpvorbpphdefdpurfpdaqv/Build/Intermediates/SfM_OpenMVG.build/Debug/SfM_incremental_unified.build/Objects-normal/x86_64/computeMatches.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Resolution: As it turns out the hpp-file I was referring to includes a file that defines a function with same name as one of the functions in the original file and that is what cause the linker error. I have no idea why this even worked in the first place when just including the .hpp file once.
I know you said you've done this but replace
static double logcombi(size_t k, size_t n)
with
inline double logcombi(size_t k, size_t n)
and fully recompile.
To distribute your library in a header is a very strange thing. Since you have access to the source code, I'd just create the corresponding cpp file, copy & paste the code from the header to the cpp file, and then remove the bodies of the functions in the header.
I'd also remove the static functions from the header: it actually does not make much sense to have a static (private) function in the file in which you expect to find the exportable symbols (i.e., public functions).
Finally, are you sure there are only functions in that hpp file? If there were constants it would be equally problematic. In that case I'd keep the declaration with an extern in the header and would move the constant to the cpp file.
I know, it is a lot of work (well, not so much, actually), but it is also the only sensible way to arrange things.
Hope this helps.
As far as I can see, you implement such functions in the same place you declare them. This is the cause of error on double inclusion. So far, you have two alternatives:
Employ "inline" clause as recommended by Bathsheba. The problem is: "inline" is just a hint. Compiler may refuse your attempts of inlining the functions, even if "forceinline" asked. It seems, your case is not inline-compatible as it not helps you.
Split a function as usual .H + .CPP pair, so that client code would include the .H file and then link with a lib containing the .CPP
The fact you name your file as .HPP instead of .H does nothing with the way how compiler treats it. You can use any arbitrary extension for a file and then include it as a header. So, naming convention here is no more than good programming style (.H for C/C++ compatible headers, .HPP for C++ only).
I learned that if I compile main.cpp the compiler simply replaces all includes with the actual content of the file i.e. #include "LongClassName.h" with the text in that file. This is done recursively in LongClassName.h. In the end the compiler sees a huge "virtual" file with the complete code of all .cpp and .h files.
But it seems to be much more complicated in real projects. I had a look at the Makefile Eclipse created for my Qt project and it seems that there is an entry for every file named file.o and its dependencies are file.cpp and file.h. So that means that eclipse compiles each .cpp separately(?)
Does that mean that class.cpp will know nothing about global stuff in main.cpp or a class in higher include hirarchy?
I stumbled upon this problem while trying to create an alias for a long class name. It is my main class and I wanted to call static functions with a shorter name: Ln::globalFunction() instead of LongClassName::globalFunction()
I have a class LongClassName whose header I include in main.cpp. This is the main class. All other classes are included in it.
LongClassName.h
#define PI 3.14159265
#include <QDebug>
Class LongClassName
{
...
public:
...
private:
...
};
typedef LongClassName Ln;
LongClassName.cpp
#include "Class1.h"
#include "Class2.h"
#include "Class3.h"
/*implementations of LongClassName's functions*/
So I assumed that when the code is included in one single "virtual" file by the compiler every class will be inserted after this source code and because of that every class should know that Ln is an alias for LongClassName
This didn't work
So what is the best way to propagate this alias to all classes?
I want to avoid including LongClassname.h in all classes because of reverse dependencies. LongClassName includes all other classes in its implementation. And almost all the other classes use some static functions of LongClassName.
(At the moment I have a seperate class Ln but try to merge it with LongClassName because it seems more logical.)
The compiler knows how to compile a .cpp file (if it's a cpp compiler) into a .o file called 'object file', which is your code translated (and probably manipulated, optimized, etc.) to a machine code. Actually the compiler creates an assembly code, which is translated to machine code by the assembler.
So each cpp file is compiled to a different object file, and knows nothing about variables declared in other cpp files, unless you include declarations you want the object file to know about, either in the cpp file or in an h file it includes.
Although the compilation is done separately for each cpp, the linker links all object files to a single executable (or a library), so a variable declared in the global namespace is indeed global, and every declaration not explicitly placed in a named
namespace is placed in the global namespace.
You will probably benefit from reading about all stages of "compiling", for example here: http://www.network-theory.co.uk/docs/gccintro/gccintro_83.html
In the end the compiler sees a huge "virtual" file with the complete code of all .cpp and .h files.
This is wrong. In .cpps you should include just the .hs (or .hpps if you like), almost never the .cpps; the .h in general just contain the declarations of the classes and of the methods, and not their actual body1 (i.e. their definition), so when you compile each .cpp the compiler still knows nothing about the definition of the functions defined in other .cpps, it just knows their declaration, and with it it can perform syntactical checks, generate code for function calls, ... but still it will generate an "incomplete" object file (.o), that will contain several "placeholders" ("here goes the address of this function defined somewhere else" "here goes the address of this extern variable" and so on)
After all the object files have been generated, it's the linker that have to take care of these placeholders, by plumbing all the object files together and linking their references to the actual code (which now can be found, since we have all the object files).
For some more info about the classical compile+link model, see here.
Does that mean that class.cpp will know nothing about global stuff in main.cpp or a class in higher include hirarchy?
Yes, it's exactly like that.
But why doesn't the Makefile created by eclipse simply compile main.cpp. Why isn't this enough? main.cpp contains all the dependencies. Why compile every .cpp separately?
main.cpp doesn't contain all the code, but just the declarations. You don't include all the code in the same .cpp (e.g. by including the other .cpps) mainly to decrease compilation time.
I want to avoid including LongClassname.h in all classes because of reverse dependencies. LongClassName includes all other classes in its implementation. And almost all the other classes use some static functions of LongClassName.
If you use header guards, you shouldn't have problems.
1. Ok, they also contain inline and template functions, but they are the exception, not the rule.