Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.53/64: Рейтинг темы: голосов - 64, средняя оценка - 4.53
0 / 0 / 0
Регистрация: 20.11.2018
Сообщений: 23

Ошибка multiple definition при сборке в QT Creator

21.11.2018, 05:33. Показов 14172. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Через консоль (c помощью g++) программа компилируется и запускается без ошибок
В QT Creator не компилируется

/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:49: ошибка: multiple definition of `Token_stream::Token_stream()'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:58: ошибка: multiple definition of `Token_stream::putback(Token)'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:67: ошибка: multiple definition of `Token_stream::get()'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:98: ошибка: multiple definition of `ts'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:108: ошибка: multiple definition of `primary()'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:157: ошибка: multiple definition of `expression()'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:129: ошибка: multiple definition of `term()'
/mnt/98207cf8-b3d3-497c-a94c-8f0f49f15ead/projects/TasksOfBook/chapter_6/6_TASK_1_calculator/6_TASK_1_calculator.cpp:181: ошибка: multiple definition of `main'
:-1: ошибка: collect2: error: ld returned 1 exit status


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//
// This is example code from Chapter 6.7 "Trying the second version" of
// "Software - Principles and Practice using C++" by Bjarne Stroustrup
//
 
/*
    This file is known as calculator02buggy.cpp
 
    I have inserted 0 errors that should cause this not to compile
    I have inserted 3 logic errors that should cause the program to give wrong results
 
    First try to find an remove the bugs without looking in the book.
    If that gets tedious, compare the code to that in the book (or posted source code)
 
    Happy hunting!
 
*/
 
#include "../../std_lib_facilities.h"
 
//------------------------------------------------------------------------------
 
class Token {
public:
    char kind;        // what kind of token
    double value;     // for numbers: a value
    Token(char ch)    // make a Token from a char
        :kind(ch), value(0) { }
    Token(char ch, double val)     // make a Token from a char and a double
        :kind(ch), value(val) { }
};
 
//------------------------------------------------------------------------------
 
class Token_stream {
public:
    Token_stream();   // make a Token_stream that reads from cin
    Token get();      // get a Token (get() is defined elsewhere)
    void putback(Token t);    // put a Token back
private:
    bool full {false};        // is there a Token in the buffer?
    Token buffer;     // here is where we keep a Token put back using putback()
};
 
//------------------------------------------------------------------------------
 
// The constructor just sets full to indicate that the buffer is empty:
Token_stream::Token_stream()
:full(false), buffer(0)    // no Token in buffer
{
}
 
//------------------------------------------------------------------------------
 
// The putback() member function puts its argument back into the Token_stream's buffer:
void Token_stream::putback(Token t)
{
    if (full) error("putback() into a full buffer");
    buffer = t;       // copy t to buffer
    full = true;      // buffer is now full
}
 
//------------------------------------------------------------------------------
 
Token Token_stream::get()
{
    if (full) {       // do we already have a Token ready?
        // remove token from buffer
        full=false;
        return buffer;
    }
 
    char ch;
    cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)
 
    switch (ch) {
    case '=':    // for "print"
    case 'x':    // for "quit"
    case '(': case ')': case '+': case '-': case '*': case '/':
        return Token(ch);        // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        {
            cin.putback(ch);         // put digit back into the input stream
            double val;
            cin >> val;              // read a floating-point number
            return Token('8',val);   // let '8' represent "a number"
        }
    default:
        error("Bad token");
    }
}
 
//------------------------------------------------------------------------------
 
Token_stream ts;        // provides get() and putback()
 
//------------------------------------------------------------------------------
 
double expression();    // declaration so that primary() can call expression()
 
//------------------------------------------------------------------------------
 
// deal with numbers and parentheses
double primary()
{
    Token t = ts.get();
    switch (t.kind) {
    case '(':    // handle '(' expression ')'
        {
            double d = expression();
            t = ts.get();
            if (t.kind != ')') error("')' expected");
            return d;
        }
    case '8':            // we use '8' to represent a number
        return t.value;  // return the number's value
    default:
        error("primary expected");
    }
}
 
//------------------------------------------------------------------------------
 
// deal with *, /, and %
double term()
{
    double left = primary();
    Token t = ts.get();        // get the next token from token stream
 
    while(true) {
        switch (t.kind) {
        case '*':
            left *= primary();
            t = ts.get();
        case '/':
            {
                double d = primary();
                if (d == 0) error("divide by zero");
                left /= d;
                t = ts.get();
                break;
            }
        default:
            ts.putback(t);     // put t back into the token stream
            return left;
        }
    }
}
 
//------------------------------------------------------------------------------
 
// deal with + and -
double expression()
{
    double left = term();      // read and evaluate a Term
    Token t = ts.get();        // get the next token from token stream
 
    while(true) {
        switch(t.kind) {
        case '+':
            left += term();    // evaluate Term and add
            t = ts.get();
            break;
        case '-':
            left -= term();    // evaluate Term and subtract
            t = ts.get();
            break;
        default:
            ts.putback(t);     // put t back into the token stream
            return left;       // finally: no more + or -: return the answer
        }
    }
}
 
//------------------------------------------------------------------------------
 
int main()
try
{
    cout << "Добро пожаловать в программу калькулятор!" << endl;
    cout << "Вводите выражения с числами с плавающей точкой." << endl;
    while (cin) {
        Token t = ts.get();
        double val;
 
        if (t.kind == 'x') break; // 'q' for quit
        if (t.kind == '=')        // ';' for "print now"
            cout << "=" << val << '\n';
        else
            ts.putback(t);
        val = expression();
    }
    keep_window_open();
}
catch (exception& e) {
    cerr << "error: " << e.what() << '\n';
    keep_window_open();
    return 1;
}
catch (...) {
    cerr << "Oops: unknown exception!\n";
    keep_window_open();
    return 2;
}
 
//------------------------------------------------------------------------------


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
   std_lib_facilities.h
*/
 
/*
    simple "Programming: Principles and Practice using C++ (second edition)" course header to
    be used for the first few weeks.
    It provides the most common standard headers (in the global namespace)
    and minimal exception/error support.
 
    Students: please don't try to understand the details of headers just yet.
    All will be explained. This header is primarily used so that you don't have
    to understand every concept all at once.
 
    By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
 
    Revised April 25, 2010: simple_error() added
    
    Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
    Revised November 28 2013: add a few container algorithms
    Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
*/
 
#ifndef H112
#define H112 251113L
 
 
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
 
//------------------------------------------------------------------------------
 
 
//------------------------------------------------------------------------------
 
typedef long Unicode;
 
//------------------------------------------------------------------------------
 
using namespace std;
 
template<class T> string to_string(const T& t)
{
    ostringstream os;
    os << t;
    return os.str();
}
 
struct Range_error : out_of_range { // enhanced vector range error reporting
    int index;
    Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i) { }
};
 
 
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
    using size_type = typename std::vector<T>::size_type;
 
#ifdef _MSC_VER
    // microsoft doesn't yet support C++11 inheriting constructors
    Vector() { }
    explicit Vector(size_type n) :std::vector<T>(n) {}
    Vector(size_type n, const T& v) :std::vector<T>(n,v) {}
    template <class I>
    Vector(I first, I last) : std::vector<T>(first, last) {}
    Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
    using std::vector<T>::vector;   // inheriting constructor
#endif
 
    T& operator[](unsigned int i) // rather than return at(i);
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
    const T& operator[](unsigned int i) const
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
};
 
// disgusting macro hack to get a range checked vector:
#define vector Vector
 
// trivially range-checked string (no iterator checking):
struct String : std::string {
    using size_type = std::string::size_type;
//  using string::string;
 
    char& operator[](unsigned int i) // rather than return at(i);
    {
        if (i<0||size()<=i) throw Range_error(i);
        return std::string::operator[](i);
    }
 
    const char& operator[](unsigned int i) const
    {
        if (i<0||size()<=i) throw Range_error(i);
        return std::string::operator[](i);
    }
};
 
 
namespace std {
 
    template<> struct hash<String>
    {
        size_t operator()(const String& s) const
        {
            return hash<std::string>()(s);
        }
    };
 
} // of namespace std
 
 
struct Exit : runtime_error {
    Exit(): runtime_error("Exit") {}
};
 
// error() simply disguises throws:
inline void error(const string& s)
{
    throw runtime_error(s);
}
 
inline void error(const string& s, const string& s2)
{
    error(s+s2);
}
 
inline void error(const string& s, int i)
{
    ostringstream os;
    os << s <<": " << i;
    error(os.str());
}
 
 
template<class T> char* as_bytes(T& i)  // needed for binary I/O
{
    void* addr = &i;    // get the address of the first byte
                        // of memory used to store the object
    return static_cast<char*>(addr); // treat that memory as bytes
}
 
 
inline void keep_window_open()
{
    cin.clear();
    cout << "Please enter a character to exit\n";
    char ch;
    cin >> ch;
    return;
}
 
inline void keep_window_open(string s)
{
    if (s=="") return;
    cin.clear();
    cin.ignore(120,'\n');
    for (;;) {
        cout << "Please enter " << s << " to exit\n";
        string ss;
        while (cin >> ss && ss!=s)
            cout << "Please enter " << s << " to exit\n";
        return;
    }
}
 
 
 
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s)  // write ``error: s and exit program
{
    cerr << "error: " << s << '\n';
    keep_window_open();     // for some Windows environments
    exit(1);
}
 
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
 
 
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
    R r = R(a);
    if (A(r)!=a) error(string("info loss"));
    return r;
}
 
// random number generators. See 24.7.
 
 
 
inline int randint(int min, int max) { static default_random_engine ran; return uniform_int_distribution<>{min, max}(ran); }
 
inline int randint(int max) { return randint(0, max); }
 
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
 
// container algorithms. See 21.9.
 
template<typename C>
using Value_type = typename C::value_type;
 
template<typename C>
using Iterator = typename C::iterator;
 
template<typename C>
    // requires Container<C>()
void sort(C& c)
{
    std::sort(c.begin(), c.end());
}
 
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
    std::sort(c.begin(), c.end(), p);
}
 
template<typename C, typename Val>
    // requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
    return std::find(c.begin(), c.end(), v);
}
 
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
    return std::find_if(c.begin(), c.end(), p);
}
 
#endif //H112
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
21.11.2018, 05:33
Ответы с готовыми решениями:

Ошибка multiple definition of main при наследовании
Всем привет. Проблема описана много где в интернете , но я так и не смог понять в чём косяк у меня. Помогите разобраться. Есть...

При сборке проекта возникает ошибка: Multiple definition
Добрый день! Пытаюсь собрать следующую программу с Github'а https://github.com/222464/NeoRL. Делаю cmake, make. Когда делаю make,...

Ошибка multiple definition
В строке 4 компилятор выдает ошибку &quot;multiple definition of 'fin'&quot;. Проблема в том, что в этой строке вообще нет слова fin. Объясните,...

4
2784 / 1937 / 570
Регистрация: 05.06.2014
Сообщений: 5,602
21.11.2018, 05:57
Цитата Сообщение от lo-st Посмотреть сообщение
ошибка: multiple definition of `Token_stream::Token_stream()'
Дальше должна быть строчка "first defined here". Строчку в студию.
Алсо, может все же покрасить в зеленый цвет и взять код короче раз этак в несколько?
0
0 / 0 / 0
Регистрация: 20.11.2018
Сообщений: 23
21.11.2018, 07:31  [ТС]
Цитата Сообщение от Renji Посмотреть сообщение
Дальше должна быть строчка "first defined here". Строчку в студию.
Такой строчки нету

Цитата Сообщение от Renji Посмотреть сообщение
Алсо, может все же покрасить в зеленый цвет и взять код короче раз этак в несколько?
Зачем мне брать другой код?
Этот код для обучения по книге Страутруппа, на этом калькуляторе завязаны еще две главы в книге, также задания и упражнения к главам

Добавлено через 4 минуты
6_TASK_1_calculator.cpp:49: ошибка: multiple definition of `Token_stream::Token_stream()'
6_TASK_1_calculator.cpp:58: ошибка: multiple definition of `Token_stream:: putback(Token)'
6_TASK_1_calculator.cpp:67: ошибка: multiple definition of `Token_stream::get()'
6_TASK_1_calculator.cpp:98: ошибка: multiple definition of `ts'
6_TASK_1_calculator.cpp:108: ошибка: multiple definition of `primary()'
6_TASK_1_calculator.cpp:157: ошибка: multiple definition of `expression()'
6_TASK_1_calculator.cpp:129: ошибка: multiple definition of `term()'
6_TASK_1_calculator.cpp:181: ошибка: multiple definition of `main'
:-1: ошибка: collect2: error: ld returned 1 exit status
0
2784 / 1937 / 570
Регистрация: 05.06.2014
Сообщений: 5,602
21.11.2018, 07:36
Лучший ответ Сообщение было отмечено lo-st как решение

Решение

Цитата Сообщение от lo-st Посмотреть сообщение
Такой строчки нету
Тогда, единственная мысль - проверить pro файл на предмет того что calculator.cpp каким-то образом оказался указан там дважды.
2
0 / 0 / 0
Регистрация: 20.11.2018
Сообщений: 23
21.11.2018, 07:40  [ТС]
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt
 
SOURCES += \
    6_TASK_1_calculator.cpp \
    6_TASK_1_calculator.cpp
 
HEADERS += \
    ../../std_lib_facilities.h
 
DISTFILES += \
    bin/6_TASK_1_calculator
Да действительно!! Спасибо!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
21.11.2018, 07:40
Помогаю со студенческими работами здесь

Ошибка multiple definition
Ошибка multiple definition of `SocketTest::bytesWritten(long long)' подскажите в чем проблема #ifndef SOCKETTEST_H #define...

Ошибка multiple definition of `Start'
так объявляю этот старт, на который ругается: void **Start В конструкторе формы делаю так: Start=NULL; Как побороть данную...

Multiple definition ошибка, использую extern
Доброго времени суток. Столкнулся с проблемой, описанной в шапке темы. Замысел заключается в создании файла, где будут храниться все...

CooCox. Ошибка multiple definition of `_impure_ptr
Пишу в Coosox програмульку на STM32F405. Проблема в том, что при использовании sscanf выкидает такую ошибку: d:/program...

Multiple definition при специализации функции
Кто может объяснить, почему в этом коде multiple definition для void foo&lt;Test&gt;(Test const&amp;) ? #ifndef TEST_H #define TEST_H class...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru