dimmigen dimmigen - 4 months ago 12
C++ Question

"multiple definition of ..." using arpackpp

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 function
std::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 function
std::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?

Answer

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.