1

main.cpp

#include <iostream>
#include "vector.hpp"


int main(){
  lasd::Vector<int> Vector_int(400);
}

vector.cpp

#include <iostream>
#include "vector.hpp"


template <class Data>
lasd::Vector<Data>::Vector(Data a){
  this->Pointer = a;
}

vector.hpp

#ifndef VECTOR_HPP
#define VECTOR_HPP

namespace lasd{

template <typename Data>
class Vector{
  private:
    int dimensione;
    Data Pointer;

  public:
    Vector();
    Vector(Data a);

};

}

#include "vector.cpp"

#endif

ERRORI

./vector.cpp:6:21: error: redefinition of
      'Vector<Data>'
lasd::Vector<Data>::Vector(Data a){
                    ^
./vector.cpp:6:21: note: previous definition is
      here
lasd::Vector<Data>::Vector(Data a){
                    ^
1 error generated.

I can’t figure out what the error in my code is. Can you please tell me what’s wrong. If you could kindly give me a suggestion/advice I would be grateful.I’ve been banging my head all morning. PS I have been learning c++ for a very short time.

Wozy Wors
  • 51
  • 7

1 Answers1

2

The problem is in vector.hpp

#include "vector.cpp"

Remove this line.

But then you'll have another problem which is that template code must go in header files. So move all the code from "vector.cpp" into "vector.h" and delete "vector.cpp"

john
  • 85,011
  • 4
  • 57
  • 81
  • OP already does `#include "vector.cpp"` at the end of the header file. No need to copy the contestants manually – Aykhan Hagverdili Apr 04 '20 at 13:15
  • 2
    Moving the contents manually is a better solution than having a cpp file included in a header file. – john Apr 04 '20 at 13:16
  • Citation needed – Aykhan Hagverdili Apr 04 '20 at 13:17
  • Not really I came up with that one myself. If you have a cpp file someone might be tempted to compile it directly (as the OP clearly has). – john Apr 04 '20 at 13:17
  • regarding the "build.sh" I do "g++ -o main main.cpp" while the body of the file "vector.cpp" I put it after endif or inside? – Wozy Wors Apr 04 '20 at 13:18
  • @WozyWors My simple solution to your problem is to delete vector.cpp, if you want to keep it, then you're going to have to ask someone else what to do. I'm not going to advise on bad practice. Template code belongs in header files. As you can read in the linked question. – john Apr 04 '20 at 13:20