Error c2365 c

I'm trying to make a program that compresses and decompresses files. I want to make an enum like this for the type of operation: typedef enum { COMPRESS, DECOMPRESS } operation;. Problem is, I get 4

I’m trying to make a program that compresses and decompresses files. I want to make an enum like this for the type of operation: typedef enum { COMPRESS, DECOMPRESS } operation;.
Problem is, I get 4 errors:

Error   1   error C2365: 'COMPRESS' : redefinition; previous definition was 'enumerator'
Error   2   error C2086: 'COMPRESS' : redefinition
Error   3   error C2365: 'DECOMPRESS' : redefinition; previous definition was 'enumerator'
Error   4   error C2086: 'DECOMPRESS' : redefinition

I don’t get what’s wrong because I made an enum just like that for boolean values, and it works fine: typedef enum { FALSE, TRUE } boolean;.

EDIT:
I was requested to add the entire .h file the typedef is in:

#include <stdio.h>
typedef enum { COMPRESS, DECOMPRESS } operation;
void compress(FILE * file);
void compressArchive(FILE * files[]);
void decompress(FILE * file);
void decompressArchive(FILE * files[]);

and as n.m. said I do #include "huffman.h" in another file, general.h (that needs the operation type) and in huffman.c, and in main.c.

What did I do wrong?

Thanks.

  • Remove From My Forums
  • Question

  • I have an enum in my header file

    typedef enum tagSTATE

    {

                    TIME_STAMP           = 0,

        LOOP_DETECTION       = 1,

                    MAC_DETECTION        = 2,

                    THREE_DETECTION      = 3,

                    SPACE_DETECTION      = 4,

                    TYPE_DETECTION       = 5,

                    OVER                 = 6,

                    DEVICE_TYPE          = 7,

    }STATE;

    I declared it as a new type, outside all my classes.

    When I built it in VC++ 2003, it’s ok. But in VC++2013, the compiler reports that

    > : error C2365: ‘DWORD’ : redefinition; previous definition was

    > ‘typedef’ 1>         

    C:Program FilesWindows

    > Kits8.1Includesharedminwindef.h(156) : see declaration of ‘DWORD’

    When i use F12 to find the reference it is pointing out to below header file with the definition

        C:Program FilesWindows Kits8.1Includeumwinioctl.h

        #define DEVICE_TYPE DWORD

    My project has not any #include «winioctl.h» line. But when i check showincludes during compilation it was used indirectly

    Help me for a solution !

    I tried changing name ‘DEVICE_TYPE’ to ‘DEVICE_TYPE1’,

    the error was removed, but in my project has so many place I used ‘DEVICE_TYPE’.

    I don’t want to change it :(

Answers

  • Try adding

    #undef DEVICE_TYPE

    after #include «windows.h» or whatever windows header drags in winioctl.h

    • Proposed as answer by

      Friday, June 5, 2015 11:51 PM

    • Marked as answer by
      Shu 2017
      Tuesday, June 16, 2015 10:01 AM

  • Forum
  • Beginners
  • Error C2365

Error C2365

Goal:

Use a struct that has 4 fields, input to those fields, and pass to function to display.

Problem:

(38) : error C2365: ‘displaySData’ : redefinition; previous definition was ‘data variable’

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
#include <iostream>
#include <string>
using namespace std;

//prototypes
void displaySData(MovieData, MovieData);

struct MovieData
{
	string Title;
	string Director;
	string YearReleased;
	string RunTime;
};

int main()
{
	MovieData data1;
	MovieData data2;

	// Get input for struct var 1
	cout<<"Enter the title of the movie:n";
	cin>>data1.Title;
	cout<<"Enter the director of the movie:n";
	cin>>data1.Director;
	// Get input for struct var 2
	cout<<"Enter the release date (year) of the movie:n";
	cin>>data2.YearReleased;
	cout<<"Enter the run time (minutes) of the movie:n";
	cin>>data2.RunTime;
	// Function for display
	displaySData(data1, data2);
	system("Pause");
	return 0;
}

void displaySData(MovieData d1, MovieData d2)
{
	cout<<d1.Title<<"n";
	cout<<d1.Director<<"n";
	cout<<d2.YearReleased<<"n";
	cout<<d2.RunTime<<"n";
}

C++ Masters.. Please help me..

The compiler didn’t know what to do with the prototype because MovieData is defined after the prototype. Switch the order it will compile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

struct MovieData
{
	string Title;
	string Director;
	string YearReleased;
	string RunTime;
};

//prototypes
void displaySData(MovieData, MovieData);

Last edited on

Hope this helps.

I modified your code a little bit. Instead of cin, I am using getline(). That way it reads an entire line and not just the first string. Also I am not sure why you using data2 to store year and length, so I removed it completely from the code and swapped the struct with function header. It compiles and runs as expected.

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
#include <iostream>
#include <string>
using namespace std;

//prototypes


struct MovieData
{
	string Title;
	string Director;
	string YearReleased;
	string RunTime;
};

void displaySData(MovieData);

int main()
{
	MovieData data1;
	

	// Get input for struct var 1
	cout << "Enter the title of the movie:n";
	getline(cin, data1.Title);
	cout << "Enter the director of the movie:n";
	getline(cin, data1.Director);
	cout << "Enter the release date (year) of the movie:n";
	getline(cin, data1.YearReleased);
	cout << "Enter the run time (minutes) of the movie:n";
	getline(cin, data1.RunTime);
	// Function for display
	displaySData(data1);
	system("Pause");
	return 0;
}

void displaySData(MovieData d1)
{
	cout << d1.Title << "n";
	cout << d1.Director << "n";
	cout << d1.YearReleased << "n";
	cout << d1.RunTime << "n";
}

@ mobotus
Why couldn’t it just tell me that! LOL

@ art1986
Yeah, my instructions are to use 2 variables. Also, what is with the getline()? My book would basically tell me to use after each input (after the first):

cin.ignore();
getline(cin, data1.Director);

I literally started learning this chapter 3 hours ago so forgive my ignorance

Last edited on

Lets say the movie title is Harry Potter. When you first cin, it will assign only Harry because it reads until it encounters whitespace, Potter will remain in buffer until next cin. getline() on the other hand will read an entire line.

cin.ignore() will clear out your cin buffer of any left over user input.

cin.ignore(1000, ‘n’) — will clear out 1000 characters or until it reaches whitespace.

Hope this helps.

Topic archived. No new replies allowed.

Hi all.
I have an enum like that

enum Dmode {
        select,
        place,
        place,
        text,
        paste 
};

I declared it as a new type, outside all my classes. When I built it in VC++ 2005, it’s ok. But in VC++2010, the compiler reports that

error C2365: 'select' : redefinition; previous definition was 'function'
1>          c:program filesmicrosoft sdkswindowsv7.0aincludewinsock2.h(1915) : see declaration of 'select'

same to ‘connect’
My project has not any #include «winsock2.h» line.

If you have any solution, please give me.

Thank you so much!

Add: I tried changing name ‘select’ to ‘select’, the error was removed, but in my project has so many place I used ‘select’. I don’t want to change it :(

Updated 27-Aug-12 19:38pm

Comments


1 solution

Solution 1

Two things:
1. You may not have #included winsock2.h directly, but some other file you DID #include, included it in turn, either directly or indirectly through yet another #include. (A quick search on my system shows 21 files containing «winsock2.h» in the include directory.)
2. If you want to reuse names that conflict with system names, consider using namespaces[^]
Alternatively, you can use the Refactor/Rename command in VS to do an intelligent renaming of YOUR symbol.

Peter

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

pormonik

0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

1

Небольшая ошибка в программе

26.09.2011, 20:32. Показов 5301. Ответов 35

Метки нет (Все метки)


Привет друзья!Для выч.мата нужно написать программу..программа вроде бы верна(у других работает,изменена только формула.У меня выдает такую ошибку:
1)Error 2 error C2365: ‘exp’ : redefinition; previous definition was ‘function’
2)Error 3 error C2665: ‘pow’ : none of the 6 overloads could convert all the argument types(4 ошибки)
Как видно из текста программы,ругается он на функции exp и pow.Но библиотеки подключены,и видимо есть конфликт в типах значений.Не могли уважаемые форумчане подсказать в чем ошибка?Заранее огромное спасибо!

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
#include <iostream>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
double exp;
 
double f(double x) 
{
     //исходное ур-е
    return pow(exp,x)-pow(exp,(-x))-2;
    
}
double fi(double x) 
{
     //итерирующая ф-ция
    return pow(exp,(-x))+pow(exp,x);
}
 
void rass4et (double x, double E)
{
    double t=x;
    double f1,f2;
    int n=0;   //кол-во итераций
    do
    {
        x=t;
        t=fi(x);   //получение очередного приблежения к корню
        f1=f(x);
        f2=f(t);
        n=n+1;
 
        cout<<"nитерация: "<<n<<" корень: "<<x<<" f(x):"<<f(x);
    } while(!((abs(x-t)<E)&&(abs(f1-f2)<E)));
    cout<<"nРезультаты:";
cout<<"nитерация:"<<n<<" корень:"<<x<<" f(x):"<<f(x);
}
void main ()
{
setlocale( LC_ALL,"Russian" ); //подключение возможности вывода русских букв
do{
cout<<"Программа рассчёта корня нелинейного ур-я методом итерацийnn";
    double x,E;
    cout<<"Введите х: ";
    cin>>x;                 // начальное приближение
    cout<<"Введите точность Е: "; 
    cin>>E;                 //точность вычислений
    rass4et(x,E);
}while(getch()=='y');
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

26.09.2011, 20:32

Ответы с готовыми решениями:

Небольшая ошибка в программе
Все работает, но не могу понять почему вместо 5 попыток получается 6. Подскажите пожалуйста что…

Небольшая ошибка в программе
Вот решаю задачу с одного сайта, всё вроде должно работать, но не получается присвоить s значение a…

Небольшая ошибка в программе
Я полный новичок в c++, написал программу, которая проверяет, какое число больше, первое, или…

Небольшая недоработка в программе
Задача была написать программу, которая читает введенную матрицу, делает проверку значений на…

35

-=ЮрА=-

Заблокирован

Автор FAQ

26.09.2011, 20:54

2

pormonik,

Цитата
Сообщение от pormonik
Посмотреть сообщение

pow(exp,x)

C++
1
pow(exp(x),x)

или же если нужно е^х, тогда

C++
1
pow(exp(1),x

)

Добавлено через 3 минуты

Цитата
Сообщение от pormonik
Посмотреть сообщение

double exp;

— а на єто и подавно ругань будет — вы объявили константу одноимённую с именем функции, если хотите в -цию передавать e тогда так делайте
double e = exp(1); и в функции е вписывайте вместо exp(1)



1



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

26.09.2011, 20:54

 [ТС]

3

щас посмотрю.спасибо



0



-=ЮрА=-

Заблокирован

Автор FAQ

26.09.2011, 21:03

4

Вот так тогда прототипы функций сделайте

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
using namespace std;
double e = exp(1);
 
double f(double x) 
{
    return pow(e,x)-pow(e,(-x))-2;
        
}
double fi(double x) 
{
    return pow(e,(-x))+pow(e,x);
}

Добавлено через 1 минуту

Цитата
Сообщение от pormonik
Посмотреть сообщение

Сделал по вашему,теперь пишет новые ошибки:
1)Error 2 error C2365: ‘exp’ : redefinition; previous definition was ‘function’
2)Error 3 error C2668: ‘exp’ : ambiguous call to overloaded function (4 шт)

Вы невнимательны я уже написал по этому поводу

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

double exp;
— а на єто и подавно ругань будет — вы объявили константу одноимённую с именем функции, если хотите в -цию передавать e тогда так делайте
double e = exp(1); и в функции е вписывайте вместо exp(1)

Добавлено через 6 минут
pormonik, я уже 5 минут как откомпилировал ваш код использовав

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

#include <stdio.h>
using namespace std;
double e = exp(1);
double f(double x)
{
* * * * return pow(e,x)-pow(e,(-x))-2;
}
double fi(double x)
{
* * * * return pow(e,(-x))+pow(e,x);
}

, а вы?



1



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

26.09.2011, 21:06

 [ТС]

5

Ой простите,в коде забрыл убрать double exp,она ни к чему.Функция ехр это стандартная функция с++.нужно е^х.изменение на pow(exp(1),x) дало новую ошибку (4 шт):
1)Error 2 error C2668: ‘exp’ : ambiguous call to overloaded function

Добавлено через 1 минуту
Простите,не видел ваших новых сообщений,действительно был невнимателен щас все переделаю!!!Огромное спасибо!



0



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

28.09.2011, 15:01

 [ТС]

6

А у вас запустилась программа?У меня снова выдает ошибку:

Error 2 error C2668: ‘exp’ : ambiguous call to overloaded function (1шт)



0



-=ЮрА=-

Заблокирован

Автор FAQ

28.09.2011, 15:40

7

Цитата
Сообщение от pormonik
Посмотреть сообщение

А у вас запустилась программа?У меня снова выдает ошибку:
Error 2 error C2668: ‘exp’ : ambiguous call to overloaded function (1шт)

pormonik, вот вам полный код — у меня компилируется без ероров

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
#include <iostream>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <stdio.h>
using namespace std;
#include <stdio.h>
using namespace std;
double e = exp(1);
 
double f(double x) 
{
        return pow(e,x)-pow(e,(-x))-2;
        
}
double fi(double x) 
{
        return pow(e,(-x))+pow(e,x);
}
 
void rass4et (double x, double E)
{
    double t=x;
        double f1,f2;
        int n=0;   //кол-во итераций
        do
        {
                x=t;
                t=fi(x);   //получение очередного приблежения к корню
                f1=f(x);
                f2=f(t);
                n=n+1;
 
                cout<<"nитерация: "<<n<<" корень: "<<x<<" f(x):"<<f(x);
        } while(!((abs(x-t)<E)&&(abs(f1-f2)<E)));
        cout<<"nРезультаты:";
cout<<"nитерация:"<<n<<" корень:"<<x<<" f(x):"<<f(x);
}
void main ()
{
setlocale( LC_ALL,"Russian" ); //подключение возможности вывода русских букв
do{
cout<<"Программа рассчёта корня нелинейного ур-я методом итерацийnn";
        double x,E;
        cout<<"Введите х: ";
        cin>>x;                                 // начальное приближение
        cout<<"Введите точность Е: "; 
        cin>>E;                                 //точность вычислений
        rass4et(x,E);
}while(getch()=='y');
}



1



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

28.09.2011, 21:31

 [ТС]

8

Блин все также 1 ошибка…завтра уже сдавать,эта программа рушит все планы

Небольшая ошибка в программе

з.ы у меня студия 2008,в этом может быть причина?



0



-=ЮрА=-

Заблокирован

Автор FAQ

28.09.2011, 22:27

9

Цитата
Сообщение от pormonik
Посмотреть сообщение

з.ы у меня студия 2008,в этом может быть причина?

— возможно сейчас смотрю ваш скрин

Добавлено через 3 минуты
pormonik, попробуйте так
using namespace std;
#include <stdio.h>
//using namespace std;//2-й раз пространство имён указываете использовать не хорошо
#define e exp(1.0) //пробуем задефайнить а не глобал переменную сделать



1



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

28.09.2011, 22:50

 [ТС]

10

Спасибо!Запустилась,правда программа зацикливается и считает беспокнечно.У других с другой формулой работает.Формулу записал верно,проверил.Значит дело все таки в exp.Правильно ли мы делаем,что ставим exp(1.0)?



0



-=ЮрА=-

Заблокирован

Автор FAQ

28.09.2011, 23:41

11

да с этим нет проблем е в 1-й,зацикливание скорее всего в коде,его я досконально не смотре пока



0



0 / 0 / 0

Регистрация: 26.09.2011

Сообщений: 40

29.09.2011, 00:06

 [ТС]

12

Да видимо в коде.Потому что Х должен быть например 1ей,а точность Е например 0.01,видимо по условию не сходится,и цикл бесконечен.Ерунда какая то.



0



-=ЮрА=-

Заблокирован

Автор FAQ

29.09.2011, 09:31

13

pormonik,

Цитата
Сообщение от pormonik
Посмотреть сообщение

(abs(x-t)<E)

— друг fabs нужен у тебя же аргументы дабл



0



Делаю внезапно и красиво

Эксперт С++

1312 / 1227 / 72

Регистрация: 22.03.2011

Сообщений: 3,744

29.09.2011, 14:05

14

В С++ abs перегружен для всех встроенных типов.



0



-=ЮрА=-

Заблокирован

Автор FAQ

29.09.2011, 17:09

15

Цитата
Сообщение от Deviaphan
Посмотреть сообщение

В С++ abs перегружен для всех встроенных типов.

причём тут перегрузка преобразование (int)double всегда корректно???Пишешь с уверенностью а об INT_MAX и величинах double забыл, ая яй



0



Делаю внезапно и красиво

Эксперт С++

1312 / 1227 / 72

Регистрация: 22.03.2011

Сообщений: 3,744

29.09.2011, 17:12

16

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

преобразование (int)double всегда корректно

О_о
Ничего, что у double e+307, а у int е+9 ?
Тем более, что неявно такое молча не преобразуется.



0



-=ЮрА=-

Заблокирован

Автор FAQ

29.09.2011, 17:17

17

Цитата
Сообщение от Deviaphan
Посмотреть сообщение

Ничего, что у double e+307, а у int е+9 ?
Тем более, что неявно такое молча не преобразуется.

— ну так а что пишешь

Цитата
Сообщение от Deviaphan
Посмотреть сообщение

В С++ abs перегружен для всех встроенных типов.

я что перегрузку имел ввиду

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

друг fabs нужен у тебя же аргументы дабл

— я обращал внимание как раз на это

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

INT_MAX и величинах double забыл

Не по теме:

Deviaphan, ты сам себе уже противоречишь, иди пиши смпт лучше:D



0



Deviaphan

Делаю внезапно и красиво

Эксперт С++

1312 / 1227 / 72

Регистрация: 22.03.2011

Сообщений: 3,744

29.09.2011, 17:24

18

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

я что перегрузку имел ввиду

А о каком преобразовании ты говоришь?

Я говорю об этой перегрузке: <math.h>

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int abs( 
     int n 
  );
  long abs( 
     long n 
  );   // C++ only
  double abs( 
     double n 
  );   // C++ only
  long double abs(
     long double n
  );   // C++ only
  float abs(
     float n 
  );   // C++ only
  __int64 _abs64( 
     __int64 n 
  );



0



-=ЮрА=-

Заблокирован

Автор FAQ

29.09.2011, 17:32

19

Цитата
Сообщение от Deviaphan
Посмотреть сообщение

о каком преобразовании ты говоришь?

о том если здесь

Цитата
Сообщение от pormonik
Посмотреть сообщение

x-t

больше INT_MAX или же точность нужна до Е а x — t = 0.0001 то abs либо вернёт фикню больше x-t > INT_MAX либо ноль если x-t = 0.0001, а в программе нужно именно точное значение x-t, вот и всё



0



Делаю внезапно и красиво

Эксперт С++

1312 / 1227 / 72

Регистрация: 22.03.2011

Сообщений: 3,744

29.09.2011, 17:36

20

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

о том если здесь

x и t — double. Их разница тоже double. С какой стати будет вызываться перегрузка не для double? Откуда в даблах взялся INT_MAX?



0



Понравилась статья? Поделить с друзьями:
  • Error c2338 windows headers require the default packing option
  • Error c231 redefinition
  • Error c2259 невозможно создать экземпляр абстрактного класса
  • Error c2248 cannot access private member declared in class
  • Error c2238 непредвиденные лексемы перед