Ошибка компилятора c2371

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

I have the following code:

#include <stdio.h>
#include <stdlib.h>

// helping
void sortint(int numbers[], int array_size)
{
  int i, j, temp;

  for (i = (array_size - 1); i > 0; i--)
  {
    for (j = 1; j <= i; j++)
    {
      if (numbers[j-1] > numbers[j])
      {
        temp = numbers[j-1];
        numbers[j-1] = numbers[j];
        numbers[j] = temp;
      }
    }
  }
}

// exer1 - A

void sort(int** arr, int arrsize) {
    int i = 0;
    // sort....
    for(; i < arrsize; ++i) {
        sortint((*(arr+i))+1,  **(arr+i));
    }
}

// Exer1 - B

void print(int** arr, int arrsize) {
    int i = 0, j, size, *xArr;
    for(; i < arrsize; ++i) {
        size = **(arr+i);
        xArr = *(arr+i);
        printf("size: %d: ", size);
        // print elements
        for(j = 1; j <= size; ++j) printf("[%d], ", *(xArr+j));
        printf("\n");
    }
}

// Exer2:

void exera() {
    int* ptr = (int*)malloc(sizeof(int));
    if(!ptr) exit(-1);
    eb(ptr);
    free(ptr);
}

void eb(int* ptr) {
    int* arr = (int*) malloc(sizeof(int) * (*ptr));
    int i = 0;
    for(; i < *ptr; ++i) scanf("%d", arr+i);
    ec(arr, *ptr);
}

void ec(int* arr, int size) {
    int i;
    sortint(arr, size);
    for(i = 0; i < size; ++i) printf("[%d], ", *(arr+i));
}

int main() {
    // Exer1:
    int a[] = {4,3,9,6,7};
    int b[] = {3,2,5,5};
    int c[] = {1,0};
    int d[] = {2,1,6};
    int e[] = {5,4,5,6,2,1};
    int* list[5] = {a,b,c,d,e};
    sort(list, 5); // A
    print(list, 5); // B
    printf("\n\n\n\n\n");
    // Exer2:
    exera();
    fflush(stdin);
    getchar();
    return 0;
}

I get these errors:

Error   2   error C2371: 'eb' : redefinition; different basic types
source.c    56

Error   4   error C2371: 'ec' : redefinition; different basic types 
source.c    63

Warning 1   warning C4013: 'eb' undefined; assuming extern returning int    
source.c    52

Warning 3   warning C4013: 'ec' undefined; assuming extern returning int    
source.c    60

I tried to change function names — for nothing.

Why is that error is being shown? I’m using Visual C++ Express 2010.

  • Remove From My Forums
  • Question

  • Hello:

    I am by no means a VC++ guru, so please be patient with me.

    I have inherited a project coded in C++ that was originally compiled using VS2003, and I am now trying to convert it so that I can work on it in VS2008 Pro.

    The conversion process goes smooth. I get no errors.

    However, when I try to compile the project, I get an error C2371 — redefinition different basic types.

    Here is what I have been able to figure out thus far.

    The variable that is generating the error is named NETWORK_ADDRESS . It is defined once in a header file that is part of my project and is associated with it using the #include directive.

    The other place it is defined is in a file called.

    C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\NtDDNdis.h

    Here is where I get stuck. I do not have an include statement in my project for this file. I have no idea why the compiler is even looking at this file. It should not be a part of this project.

    How do I set VS2008 up so that it does not try to use this file?

    Thank you in advance for your help.

Answers

  • I have searched every header file I have included in my project, and I cannot find anyone of them that include the NtDDNdis.h file. This sure is becoming a head scratcher.

    You have to take into consideration not only the header files that you included in your project, but also the header files that are being included by the ones you included. For instance, if you include <windows.h>, it’s not enough to search for  NtDDNdis.h in <windows.h>. You also have to search in every header file included by <windows.h>. And there may be dozens of those files !!!

    Off course you don’t need to do that. Just comment out your definition of NETWORK_ADDRESS in your header file and right click on any NETWORK_ADDRESS you are using in your cpp file. Then select Go To Declaration, to see the NEWORK_ADDRESS defintion in NtDDNdis.h .

    You can also right click your project name in the solution window and select :

    Properties > Configuration Properties > C/C++ > Advanced > Show Includes > Yes

    and the compiler will provide you a listing of all included files in your project.

    • Marked as answer by

      Thursday, January 29, 2009 10:32 AM

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2371

Compiler Error C2371

11/04/2016

C2371

C2371

d383993d-05ef-4e35-8129-3b58a6f7b7b7

Compiler Error C2371

‘identifier’ : redefinition; different basic types

The identifier is already declared.

The following sample generates C2371:

// C2371.cpp
int main() {
   int i;
   float i;   // C2371, redefinition
   float f;   // OK
}

I have the following code:

#include <stdio.h>
#include <stdlib.h>

// helping
void sortint(int numbers[], int array_size)
{
  int i, j, temp;

  for (i = (array_size - 1); i > 0; i--)
  {
    for (j = 1; j <= i; j++)
    {
      if (numbers[j-1] > numbers[j])
      {
        temp = numbers[j-1];
        numbers[j-1] = numbers[j];
        numbers[j] = temp;
      }
    }
  }
}

// exer1 - A

void sort(int** arr, int arrsize) {
    int i = 0;
    // sort....
    for(; i < arrsize; ++i) {
        sortint((*(arr+i))+1,  **(arr+i));
    }
}

// Exer1 - B

void print(int** arr, int arrsize) {
    int i = 0, j, size, *xArr;
    for(; i < arrsize; ++i) {
        size = **(arr+i);
        xArr = *(arr+i);
        printf("size: %d: ", size);
        // print elements
        for(j = 1; j <= size; ++j) printf("[%d], ", *(xArr+j));
        printf("n");
    }
}

// Exer2:

void exera() {
    int* ptr = (int*)malloc(sizeof(int));
    if(!ptr) exit(-1);
    eb(ptr);
    free(ptr);
}

void eb(int* ptr) {
    int* arr = (int*) malloc(sizeof(int) * (*ptr));
    int i = 0;
    for(; i < *ptr; ++i) scanf("%d", arr+i);
    ec(arr, *ptr);
}

void ec(int* arr, int size) {
    int i;
    sortint(arr, size);
    for(i = 0; i < size; ++i) printf("[%d], ", *(arr+i));
}

int main() {
    // Exer1:
    int a[] = {4,3,9,6,7};
    int b[] = {3,2,5,5};
    int c[] = {1,0};
    int d[] = {2,1,6};
    int e[] = {5,4,5,6,2,1};
    int* list[5] = {a,b,c,d,e};
    sort(list, 5); // A
    print(list, 5); // B
    printf("nnnnn");
    // Exer2:
    exera();
    fflush(stdin);
    getchar();
    return 0;
}

I get these errors:

Error   2   error C2371: 'eb' : redefinition; different basic types
source.c    56

Error   4   error C2371: 'ec' : redefinition; different basic types 
source.c    63

Warning 1   warning C4013: 'eb' undefined; assuming extern returning int    
source.c    52

Warning 3   warning C4013: 'ec' undefined; assuming extern returning int    
source.c    60

I tried to change function names — for nothing.

Why is that error is being shown? I’m using Visual C++ Express 2010.

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
void aboutH() {
    printf("Information on hard disks");
    int j;
    _int64 FreeBytesAvailable;
    _int64 TotalNumberOfBytes;
    _int64 TotalNumberOfFreeBytes;
    LPCWSTR disk = L"I:";
    LPCWSTR diski[26] = { L"A:",L"B:",L"C:",L"D:",L"E:",L"F:",L"G:",L"H:",L"I:",L"J:",L"K:",L"L:",L"M:",L"N:"
        ,L"O:",L"P:",L"Q:",L"R:",L"S:",L"T:",L"U:",L"V:",L"W:",L"X:",L"Y:",L"Z:" };
    for (j = 0; j<26; j++)
    {
        TotalNumberOfBytes = NULL;
        TotalNumberOfFreeBytes = NULL;
        FreeBytesAvailable = NULL;
        GetDiskFreeSpaceEx(diski[j],
            (PULARGE_INTEGER)&FreeBytesAvailable,
            (PULARGE_INTEGER)&TotalNumberOfBytes,
            (PULARGE_INTEGER)&TotalNumberOfFreeBytes);
        if (GetDriveType(diski[j]) == DRIVE_FIXED)
        {
            if (TotalNumberOfBytes != 0) {
                printf("%s: ", diski[j]);
 
                
                printf("Total Memory %lf Gb, ", (long double)TotalNumberOfBytes / 1024 / 1024 / 1024);
                printf("Free %lf Gbn", (long double)TotalNumberOfFreeBytes / 1024 / 1024 / 1024);
            }
            else {
                printf("%s: ", diski[j]);
 
            
 
                printf("inactive diskn");
            }
        }
        else
        {
            continue;
        }
    }
    _getch();
    fMenu();
}

I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS.

C:Program FilesMicrosoft SDKsWindowsv6.0Aincludeodbcss.h(430) :
error C2371: ‘WCHAR’ : redefinition; different basic types 1>
C:Program FilesMicrosoft SDKsWindowsv6.0Aincludewinnt.h(289) :
see declaration of ‘WCHAR’

I don’t see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this?

Vadim Kotov's user avatar

Vadim Kotov

8,0448 gold badges48 silver badges62 bronze badges

asked Sep 3, 2008 at 17:08

Brian Stewart's user avatar

Brian StewartBrian Stewart

9,09711 gold badges53 silver badges66 bronze badges

There are a half-dozen posts on various forums around the web about this — it seems to potentially be an issue when odbcss.h is used in the presence of MFC. Most of the answers involve changing the order of included headers (voodoo debugging). The header that includes odbcss.h compiles fine in it’s native project, but when it is included in a different project, it gives this error. We even put it in the latter project’s stdafx.h, right after the base include for MFC, and still no joy. We finally worked around it by moving it into a cpp file in the original project, which does not use MFC (which should have been done anyway — but it wasn’t our code). So we’ve got a work-around, but no real solution.

answered Sep 3, 2008 at 19:04

Brian Stewart's user avatar

Brian StewartBrian Stewart

9,09711 gold badges53 silver badges66 bronze badges

This error happens when you redeclare a variable of the same name as a variable that has already been declared. Have you looked to see if odbcss.h has declared a variable you already have?

answered Sep 3, 2008 at 17:19

Craig H's user avatar

Craig HCraig H

7,94916 gold badges48 silver badges61 bronze badges

does this help?

http://bytes.com/forum/thread602063.html

Content from the thread:

Bruno van Dooren [MVP VC++] but i know the solution of this problem.
it solves by changing project setting of «Treat wchar_t as Built-in
Type» value «No (/Zc:wchar_t-)». But I am using «Xtreme Toolkit
Professional Edition» for making good look & Feel of an application,
when i fix the above problem by changing project settings a new
linking errors come from Xtreme Toolkit Library. So what i do to fix
this problem, in project setting «Treat wchar_t as Built-in Type»
value «yes» and i wrote following statements where i included wab.h
header file. You can change that setting on a per-codefile basis so
that only specific files are compiled with that particular setting. If
you can solve your problems that way it would be the cleanest
solution.

#define WIN16

#include "wab.h"

#undef WIN16

and after that my project is working fine and all the things related to WAB is also working fine. any one guide me, is that the right way
to solve this problem??? and, will this have any effect on the rest of
project?? I wouldn’t worry about it. whatever the definition, it is a
16 bit variable in both cases. I agree that it isn’t the best looking
solution, but it should work IF WIN16 has no other impact inside the
wab.h file.

Kind regards, Bruno van Dooren bruno_nos_pam_van_dooren@hotmail.com
Remove only «_nos_pam»

answered Sep 3, 2008 at 17:52

John Boker's user avatar

John BokerJohn Boker

82.3k17 gold badges96 silver badges130 bronze badges

1

  • Remove From My Forums
  • Question

  • Hello:

    I am by no means a VC++ guru, so please be patient with me.

    I have inherited a project coded in C++ that was originally compiled using VS2003, and I am now trying to convert it so that I can work on it in VS2008 Pro.

    The conversion process goes smooth. I get no errors.

    However, when I try to compile the project, I get an error C2371 — redefinition different basic types.

    Here is what I have been able to figure out thus far.

    The variable that is generating the error is named NETWORK_ADDRESS . It is defined once in a header file that is part of my project and is associated with it using the #include directive.

    The other place it is defined is in a file called.

    C:Program FilesMicrosoft SDKsWindowsv6.0AIncludeNtDDNdis.h

    Here is where I get stuck. I do not have an include statement in my project for this file. I have no idea why the compiler is even looking at this file. It should not be a part of this project.

    How do I set VS2008 up so that it does not try to use this file?

    Thank you in advance for your help.

Answers

  • I have searched every header file I have included in my project, and I cannot find anyone of them that include the NtDDNdis.h file. This sure is becoming a head scratcher.

    You have to take into consideration not only the header files that you included in your project, but also the header files that are being included by the ones you included. For instance, if you include <windows.h>, it’s not enough to search for  NtDDNdis.h in <windows.h>. You also have to search in every header file included by <windows.h>. And there may be dozens of those files !!!

    Off course you don’t need to do that. Just comment out your definition of NETWORK_ADDRESS in your header file and right click on any NETWORK_ADDRESS you are using in your cpp file. Then select Go To Declaration, to see the NEWORK_ADDRESS defintion in NtDDNdis.h .

    You can also right click your project name in the solution window and select :

    Properties > Configuration Properties > C/C++ > Advanced > Show Includes > Yes

    and the compiler will provide you a listing of all included files in your project.

    • Marked as answer by

      Thursday, January 29, 2009 10:32 AM

4 ответа

На разных форумах по всему миру есть полдюжины сообщений об этом — возможно, это проблема, когда odbcss.h используется в присутствии MFC. Большинство ответов связаны с изменением порядка включенных заголовков (отладка voodoo). Заголовок, который включает odbcss.h, компилирует в нем собственный проект, но когда он включен в другой проект, он дает эту ошибку. Мы даже поместили его в последний проект stdafx.h, сразу после того, как база включилась для MFC, и до сих пор нет радости. Мы, наконец, работали над этим, переместив его в файл cpp в исходном проекте, который не использует MFC (это должно было быть сделано в любом случае — но это был не наш код). Итак, у нас есть обход, но нет реального решения.

Brian Stewart

Поделиться

Помогает ли это?

http://bytes.com/forum/thread602063.html

Содержимое из потока:

Бруно ван Дорен [MVP VС++], но я знаю решение этой проблемы. он решает путем изменения настройки проекта «Обработать wchar_t как встроенный Введите» value «No (/Zc: wchar_t-)». Но я использую «Xtreme Toolkit Professional Edition» для хорошего восприятия и ощущения приложения, когда я исправил вышеуказанную проблему, изменив настройки проекта, новый Связывание ошибок происходит из библиотеки инструментов Xtreme Toolkit. Так что я делаю, чтобы исправить эта проблема, в настройке проекта «Обработать wchar_t как встроенный тип» значение «да», и я написал следующие инструкции, в которых я включил wab.h файл заголовка. Вы можете изменить этот параметр на основе каждого кода, чтобы что только определенные файлы скомпилированы с этой конкретной настройкой. Если вы можете решить свои проблемы таким образом, чтобы это было самое чистое Решение.

#define WIN16

#include "wab.h"

#undef WIN16

и после этого мой проект работает нормально, и все, что связано с WAB, также отлично работает. кто-нибудь мне подскажет, что правильный путь Для решения этой проблемы??? и это повлияет на остальную часть проект?? Я бы не стал беспокоиться об этом. независимо от определения, это 16-битная переменная в обоих случаях. Я согласен, что это не самый лучший решение, но оно должно работать, ЕСЛИ WIN16 не имеет другого влияния внутри wab.h.

С уважением, Бруно ван Дорен [email protected] Удалить только «_nos_pam»

John Boker

Поделиться

Эта ошибка возникает, когда вы переопределяете переменную с тем же именем, что и уже объявленная переменная. Вы посмотрели, удалось ли odbcss.h объявить переменную, которую вы уже имеете?

Craig H

Поделиться

Ещё вопросы

  • 0Лучшие практики для динамического создания списка элементов в jquery
  • 0Вторая строка повреждена после нескольких вызовов realloc
  • 1Подсчет всех символов в строке
  • 1Запрет проверки Struts 2 для определенных действий
  • 1Изменение состояния элементов управления ленты Office из других мест приложения в VSTO
  • 0Создание подписки для сайта
  • 0Асинхронный обратный вызов не был вызван в течение тайм-аута — модульное тестирование службы Typescript & Angular $ http
  • 1Node Express JS — обработка одновременных POST-запросов к серверу
  • 0Передача вновь созданного объекта на другую страницу
  • 1Идентификация таблицы в HTML
  • 0Python слишком много значений, чтобы распаковать при попытке вставить данные из словаря
  • 0плагин проверки jquery, условный удаленный вызов не работает должным образом
  • 3Рассчитать остаточное отклонение от модели логистической регрессии scikit-learn
  • 1Почему эмулятор не получает FCM Push
  • 1Никакое исключение типа AuthenticationException не может быть брошено JAVA
  • 1Ошибка проверки XML-схемы «Содержимое элемента flowPara не завершено»
  • 1Обрабатывать ложные аргументы
  • 0Как использовать угловой контроллер JS дважды
  • 0json_encode — проблема с форматированием?
  • 1Умножение матриц с использованием EJML
  • 0Экспортные перерывы HighCharts после сброса параметров диаграммы
  • 0Встроенная ширина не работает в IE при связывании с AngularJS
  • 0Twiiter Follow Button For Newsletter / Html email
  • 1Счетчик приращений многократно
  • 1Android — убийство не освобождает память?
  • 1Синтаксис JPQL LIKE со строками
  • 1Как сделать новый сервлет с помощью мастера?
  • 1Попытка анализа объекта JSON из запроса POST в Express v4 с использованием body-parser
  • 0Как получить правильные значения Cell Coordinate
  • 0Обнаружить отключение Winsock C ++
  • 0AngularJS объем этого в фабрике
  • 0Присвоение значений массива подмассиву другого массива
  • 0jQPlot Дата на оси X Интервал тика не работает
  • 0Ошибка msvcr110d.dll! memcpy при тестировании структур и массивов
  • 0как сравнить Auth :: user () -> id и user_id и выполнить команду if else в Laravel
  • 0уникальный указатель в связанном стеке
  • 0MySQL JSON_SEARCH — не работает с двойными кавычками
  • 1CasperJS не хватает памяти
  • 0Стандартный метод обработки не найденных (404) ошибок во всех видах веб-серверов
  • 1Javascript: отсутствует) после списка аргументов
  • 0Сложный SQL-запрос с переменными
  • 1Панели инструментов считаются представлениями?
  • 0Разделить 1 XML на несколько после определенного тега, используя PHP
  • 1Android — уведомление переднего плана отменяется при удалении приложения из последних приложений
  • 0Я не могу управлять разными кнопками с разными именами
  • 0Выполнение запроса занимает более 40 секунд
  • 1Ошибка: SMS API получает ошибку в приложении Android
  • 0сохранение базы данных резервных копий mysql с использованием php и пути mkdir
  • 0Элементы таблицы и неупорядоченные списки нельзя просматривать должным образом во всех версиях Internet Explorer
  • 0Показывать баннер только для определенной страны / IP-адресов?

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка кия р0626
  • Ошибка компьютера синий экран белый текст
  • Ошибка компилятора c2381
  • Ошибка климат контроля пассат б5 444
  • Ошибка контрольной суммы пзу м73

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: