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.
Related
in my current project I´m working with the arpackpp interface. The entire library is written in .h files, so that there is no need to compile the library. The problem I'm facing now - when I include some of the arpackpp header files in some of my files, which are not the main.cpp, I get the following errors:
/.../Files/Includes/../../../arpack++/include/arerror.h:163: multiple definition of ArpackError::Set(ArpackError::ErrorCode, std::string const&)'
/.../Files/Includes/../../../arpack++/include/arerror.h:163: first defined here
/tmp/ccruWhMn.o: In functionstd::iterator_traits::iterator_category std::__iterator_category(char* const&)':
/.../Files/Includes/../../../arpack++/include/arerror.h:163: multiple definition of ArpackError::code'
/.../Files/Includes/../../../arpack++/include/arerror.h:163: first defined here
/tmp/ccruWhMn.o: In functionstd::vector >::max_size() const':
for several arpackpp functions when linking all the .o files. As I have read in several threads the problem is that I actually include the instantiation of the functions, which should be normally avoided.
Because I don't want to change the whole library I included all classes and functions using arpackpp classes in main.cpp, which is getting quite messy. Is there a workaround to this problem? And why doesn't include guards (#ifndef...#endif) prevent this problem?
First of all, include guards do not help at this point as they only prevent multiple inclusions of a header in a "subtree" of your project files' dependency graph. In other words: If you include a header in two totally separated files of the same project, the c++ preprocessor will replace the #include <header.h> twice and independently by the code specified in the header. This is perfectly fine as long as the header only contains declarations.
In your case (and in the case of many other header-only libraries), definitions are provided in the headers as well. So unfortunately (as far as I know), there is no elegant way other than including definition-containing files once in your project. https://github.com/m-reuter/arpackpp/blob/master/include/README explicitly states which files contain definitions.
Some libraries, however, provide preprocessor macros to trigger the inclusion of definitions for the provided header files (e.g. https://github.com/nothings/stb). Maybe arpackpp provides similar mechanisms.
In general the easiest way to the work with header only libraries is to extend your code only using headers. Provided you use the correct header guards, this would remove the issue of multiple definitions of your code. If you have a large base of existing code then I would suggest that you rename all your *.cpp files to *.hpp (c++ header files) and then add suitable header guards. Furthermore a convenient way of handling this code of base is to create an additional header file config.hpp and include all your other headers in that file. Then in your main.c it is a simple matter of including the config.hpp file.
e.g.
// Config.hpp ------------------------------------------------=
#include "example.hpp"
#include "example1.hpp"
#include "example2.hpp"
// etc.
// main.cpp --------------------------------------------------=
#include "Config.hpp"
int main() {
// Your code here.
return 0;
}
Furthermore if you wanted to continue with your project structure it would be a simple matter of separating all your code into functions that needed to access arpackcpp directly. Then include them all into one *.cpp file, and compile into a *.o and link.
I have a question about libraries. When I write a library I have 2 files: library.h and library.cpp.
The first one contains the prototypes of the functions and the second one contains the definitions. Well, in library.cpp I include #include "library.h", so they are connected in one way, but what happens with the header? Why don't I have to write #include "library.cpp" in the header?
When I use the library in the main file, I write #include "library.h", which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly:
(1) Your library.cpp file is sent to the preprocessor.
(2) The preprocessor reads the line #include "library.h" and goes and finds the file library.h.
(3) The contents of library.h are literally copied into the library.cpp file.
(4) The library.cpp file is compiled and linked with the main file.
Thus, all of the "prototypes" in the header are copied into the top of the implementation file. .cpp files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the .cpp files.
There is a tool called linker which is responsible for link your generated object files. You should look for compilation process to understand it better.
The preprocessor pulls the header file into the CPP file, so the compiler sees the prototypes and the definitions together.
If you were to pull the CPP file into the header file, you would either send the preprocessor into an infinite loop, or by using
#ifndef __FOOBAR__
#define __FOOBAR__
(code file)
#endif
around the header AND source files you would read the file just once.
All the cpp files are compiled seperately and the code is accumulated in a big pile somewhere. The linker collects all the symbols in your code and assigns them an address within this pile. So although your file doesn't see library.cpp directly, it knows the symbols from library.h and the assigned addresses. It can then zoom directly to the required code in the big pile. Not the most technical answer I know..
It was my understanding that when you type #include "library.h" in your code the compiler is set to also load library.cpp. I was taught in school that there isn't really any way to break this connection unless you were to manually compile and link each file either using compiler commands or a makefile appropriate for the system you're using (Windows, *nix, MacOS, etc.)
You have to type #include "library.h" in the library.cpp file because that is where the function prototypes are stored. You can "cheat" and put the function prototypes in the .cpp file and just type #include "library.cpp" but this is bad practice and is generally discouraged in the programming community.
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 have a code in which I #include<linux/videodev2.h>. There are three files:
one header file- includes: stdint.h and stdlib.h. Defines a couple of functions, a struct, say abc, and some #define macros. One of the functions is
int func(int, uint32_t, size_t, abc*);
one cpp file with a lot of methods, including definition of the functions in the .h file.
one main.cpp which has main() which has a function call to the method in the .h file (complete file below). This file is only for testing purposes.
#include "head.h"
int main() {
func(5, (uint32_t)5, (size_t)5, 0);
return 0;
}
What is see is a curious case:
If I include linux/videodev2.h only in .h file, uint32_t and other things defined in this header are not accessible by the .cpp files. (erros I get are: uint32_t was not declared in this scope, and uint32_t does not name a type, among others). This happens even if the first line of the .h file is #include<linux/videodev2.h>
If I include the videodev2 header in both the cpp files, it works only if I import it (videodev2) before the .h file.
If I use func(5, (uint32_t)5, (size_t)5, (abc*)0); in the main.cpp file, I get the error that abc is not declared in this scope.
I am compiling using the command: g++ main.cpp head.cpp
I am unable to figure out why is this. I would like to include the videodev2 header in the .h file since, it is almost certain that the code using the .h file will be dependent on it. But it seems that including it in .h file has no effect at all.
I must be honest here. This was C code which I had to convert to C++. I know that I am not conforming to the best practices and standards. But why is this behaviour seen?
Remember that the #include directive indicates to the preprocessor the contents of the specified file should be treated as if they appeared directly in the source file in place of the directive (paraphrased from MSDN).
With that in mind, it seems like you are encountering improper order of #includes and also missing #includes. My guess would be that you are not including your own header file in your .cpp files. This would explain cases one and three. Consider the following files:
// header.h
// #include <linux/videodev2.h> <-- Option 1
class A {
void func(uint32_t var);
};
// header.cpp
void A::func(uint32_t var) {
// implementation
}
// main.cpp
// #include <linux/videodev2.h> <-- Option 2
#include "header.h"
// #include <linux/videodev2.h> <-- Option 3
int main() {
// implementation; something creates an instance of A and calls func
}
Now, Option 1 is not exactly desirable; it's good practice to avoid #includes in header files because they can increase build times and create unwanted dependencies. However, it will ensure that the types header.h requires are there for it to use. The essential bit is that the contents of linux/videodev2.h have to appear before the contents of header.h, anywhere that header.h is #included.
This brings me to Option 2. Option 2 will also compile correctly, because linux/videodev2.h is included before your header, and your header relies on types defined in it. Also important is that both main.cpp and header.cpp must #include "header.h", because they reference symbols declared in it.
If you were to go with Option 3, you would get compilation errors that the type uint32_t is not defined, and the compiler would point to your header file. This is because the contents of the header file appear before the contents of linux/videodev2.h, and so the compiler does not yet understand what the type uint32_t is when it encounters it.
So, given all that, you have choices: include `linux/videodev2.h' before each include of your own header file, or include it directly in your header file. I mentioned earlier that the latter is not good practice, but for your particular case, it might be the better option of the two, in case your header file needs to be included in many .cpps.
I think this would be a good opportunity to dive into precompiled headers, but I'm not as well-versed in them, so I'd leave it to someone who has more experience to explain them.
Hope this helps :)
Found the answer. There was .h.gch file in the directory. I didn't know about precompiled header. Thanks ktodisco for the insight. I still have no idea why that file was there in the first place.
I have "Hello World" code that uses function fhi from another hi.cpp file that has it's header.
Correct my if my understanding is wrong according following:
I can do include cpp file like #include "c:\c\hi.cpp" instead of using header without any problems except that fact that it looks more readable in header file.
If I include header like sample in my main program hi.h, must hi.h include hi.cpp, or it is done automatically according the same file name hi. I'm wondering how compiler knows where is function fhi body.
Is it possible to have different names for header and cpp files?
Programm:
#include "stdafx.h"
#include "c:\c\hi.h"
int _tmain(int argc, _TCHAR* argv[])
{
fhi(1);
return 0;
}
hi.h
#include <cstdlib>
#include <iostream>
int var;
int fhi(int f);
hi.cpp
#include <cstdlib>
#include <iostream>
int fhi(int f)
{
return 0;
}
must hi.h include hi.cpp
No. hi.h contains only declarations, that can be other by other .cpp files.
I'm wondering how compiler knows where is function fhi body.
It doesn't. You need to compile all *.cpp files into the object files. In your case, you will have two object files: program.o and hi.o. The linker can now take these two object files, and spit out the executable. References to other functions(in this case the actual definition of fhi(..)) is resolved in this stage.
Also why are you using absolute paths in #includes? It will break when you move the "c" directory around.
What normally happens is that the build system compiles the .cpp files into object files, that then are used to build the main executable. The means to tell this to the build system vary greatly.
One important point is that your hi.cpp must include hi.h. You should also put an include guard in hi.h, to make it safe to be included more than once in a translation unit.
I can do include cpp file like #include "c:\c\hi.cpp" instead of using
header without any problems except that fact that it looks more
readable in header file.
yes, you can do so but it is not recommended, one of the problems is encapsulation; you are not hiding implementation details. readability as you mention is also a concern, a header is easier to read since it clearly shows what methods are public.
If I include header like sample in my main program hi.h, must hi.h
include hi.cpp, or it is done automatically according the same file
name hi. I'm wondering how compiler knows where is function fhi body.
the header needs to be explicitly included in hi.cpp and any .cpp file that use the class defined in the header.
Is it possible to have different names for header and cpp files?
yes but it is not recommended, it makes it more difficult to find things.
as a general rule: think about that other programmers may want to look in your code so you need to structure it so that it is easy to read and understand as well as making it easier for you 2 years down the road to remember where things are.
In Visual Studio all CPP files included in the project will be compiled to produce OBJ files. These OBJ files will be linked together to form the EXE or DLL.
Including files are similar to pasting the contents of the file at that location. The only difference is that this pasting is done by the pre-compiler during compilation.
Finding out where a function body resides is done by the either the compiler if the function is inline or by the linker when the final binary is created.
First, if the header file is in the same directory as the source file including it, you can use just
#include "hi.h"
In other words, you don't have to use a full path. (See e.g. the inclusion of "stdafx.h".)
Second, in your header file you don't need to include other header files, unless you need types from those. In your header file you don't have anything that needed from the header files you include.
Third, you should protect header files header files from being included more than once in the same source file, this can be done with a so called include guard, on in some compiler via a special directive called #pragma once.
Fourth, in your header file you define a global variable var. This variable will then be defined in every source file you include the header file in, which will lead to errors. You need to declare the variable as extern:
extern int var;
Then in one source file you define the variable like you do now.
Fifth, you should never include source files in header file (with some special exceptions that you don't have to think about yet). Instead you add all source files to the project (I assume you are in MS VisualStudio) and it they will all be built and linked together automatically.
Sixth, since you seem to be using VisualC++, then you are probably using something called precompiled headers. This is something the compiler uses to speed up compilation. However, for this to work you have to include "stdafx.h" in all source files. That include actually has to be the first non-comment line in each source file.