Несколько объявлений конструктора в C++

Я работаю над заданием для класса и сталкиваюсь (как мне кажется, с) с основной проблемой. Я пытался найти другие ответы, но, похоже, не могу найти свою проблему.

Когда я запускаю комманду makeЯ получаю следующую ошибку:

    prog8lib.o: In function `Transform':
   .../prog8lib.cc:6: multiple definition of `Transform::Transform(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
    prog8.o:.../prog8lib.cc:6: first defined here
    prog8lib.o: In function `Transform':
   .../prog8lib.cc:6: multiple definition of `Transform::Transform(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
    prog8.o:.../prog8lib.cc:6: first defined here

Это код, который я сейчас использую. Кто-нибудь может определить мои ошибки?

Спасибо!!!

prog8.cc:

#include <iostream>
#include <string.h>
#include <stdlib.h>

#include "prog8lib.cc"

using namespace std;

int main(int argc, char** argv) {
    string start = argv[1];
    string end = argv[2];
    Transform(start, end);
}

prog8lib.cc:

#include <iostream>
#include <string>
#include <stdlib.h>
#include "prog8lib.h"

Transform::Transform(string startWord, string endWord) {
    cout << "Test" << endl;
}
Transform::~Transform() {}

prog8lib.h:

#ifndef PROG8LIB_H
#define PROG8LIB_H

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

class Transform{
private:
    string start;
    string end;
public:
    Transform(string str, string str2);
    ~Transform();
};

#endif

Makefile:

OBJ = prog8.o prog8lib.o
OPTS = -g -c -Wall -Werror

trans: $(OBJ)
        g++ -o trans $(OBJ)

prog8.o: prog8.cc
    g++ $(OPTS) prog8.cc

prog8lib.o: prog8lib.cc prog8lib.h
        g++ $(OPTS) prog8lib.cc

clean:
        rm -f *.o *~

2 ответа

Решение

+ Изменить

#include "prog8lib.cc"

в prog8.cc в

#include "prog8lib.h"

В противном случае компилятор найдет два определения Transform::Transform: однажды в prog8.cc и однажды в proglib8.cc,

Вы объявили класс в заголовочном файле, и это тот файл, который вам нужно включить в main.cpp. всегда включайте заголовочные файлы, а не файлы.cpp.

http://stackru.com/questions/333889/why-have-header-files-and-cpp-files-in-c

Другие вопросы по тегам