Error c3861 cpuid идентификатор не найден

Проблема с вызовом __cpuid в проекте Windows Forms C++/CLI WinForms Решение и ответ на вопрос 379991

1 / 1 / 0

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

Сообщений: 21

1

08.11.2011, 19:31. Показов 3473. Ответов 8


В консольном приложении __cpuid отлично вызывается

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
#include <stdio.h>
#include <string.h>
#include <intrin.h>
#include <conio.h>
#include <windows.h>
 
 
int main()
{
    int argc;
    char CPUString[0x20];
    char CPUBrandString[0x40];
    int CPUInfo[4] = {-1};
    int nSteppingID = 0;
    int nModel = 0;
    int nFamily = 0;
    int nProcessorType = 0;
    int nExtendedmodel = 0;
    int nExtendedfamily = 0;
    int nBrandIndex = 0;
    int nCLFLUSHcachelinesize = 0;
    int nAPICPhysicalID = 0;
    int nFeatureInfo = 0;
    int nCacheLineSize = 0;
    int nL2Associativity = 0;
    int nCacheSizeK = 0;
    int nRet = 0;
    unsigned    nIds, nExIds, i;
 
 
    // __cpuid with an InfoType argument of 0 returns the number of
    // valid Ids in CPUInfo[0] and the CPU identification string in
    // the other three array elements. The CPU identification string is
    // not in linear order. The code below arranges the information 
    // in a human readable form.
    __cpuid(CPUInfo, 0);
    nIds = CPUInfo[0];
    memset(CPUString, 0, sizeof(CPUString));
    *((int*)CPUString) = CPUInfo[1];
    *((int*)(CPUString+4)) = CPUInfo[3];
    *((int*)(CPUString+8)) = CPUInfo[2];
 
    // Get the information associated with each valid Id
    for (i=0; i<=nIds; ++i)
    {
        __cpuid(CPUInfo, i);
 
 
        // Interpret CPU feature information.
        if  (i == 1)
        {
            nSteppingID = CPUInfo[0] & 0xf;
            nModel = (CPUInfo[0] >> 4) & 0xf;
            nFamily = (CPUInfo[0] >> 8) & 0xf;
            nProcessorType = (CPUInfo[0] >> 12) & 0x3;
            nExtendedmodel = (CPUInfo[0] >> 16) & 0xf;
            nExtendedfamily = (CPUInfo[0] >> 20) & 0xff;
            nBrandIndex = CPUInfo[1] & 0xff;
            nCLFLUSHcachelinesize = ((CPUInfo[1] >> 8) & 0xff) * 8;
            nAPICPhysicalID = (CPUInfo[1] >> 24) & 0xff;
            nFeatureInfo = CPUInfo[3];
        }
    }
 
    // Calling __cpuid with 0x80000000 as the InfoType argument
    // gets the number of valid extended IDs.
    __cpuid(CPUInfo, 0x80000000);
    nExIds = CPUInfo[0];
    memset(CPUBrandString, 0, sizeof(CPUBrandString));
 
    // Get the information associated with each extended ID.
    for (i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);
 
 
        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
            memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000003)
            memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000004)
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000006)
        {
            nCacheLineSize = CPUInfo[2] & 0xff;
            nL2Associativity = (CPUInfo[2] >> 12) & 0xf;
            nCacheSizeK = (CPUInfo[2] >> 16) & 0xffff;
        }
    }
 
    // Display all the information in user-friendly format.
 
    printf_s("nnCPU String: %sn", CPUString);
 
 
    if  (nExIds >= 0x80000004)
        printf_s("nCPU Brand String: %sn", CPUBrandString);
 
    if  (nExIds >= 0x80000006)
    {
        printf_s("Cache Line Size = %dn", nCacheLineSize);
        printf_s("L2 Associativity = %dn", nL2Associativity);
        printf_s("Cache Size = %dKn", nCacheSizeK);
    }
 
    if (IsProcessorFeaturePresent(PF_3DNOW_INSTRUCTIONS_AVAILABLE))  
        printf_s("nПоддержует технологию");
    
 
 
getch();
return  nRet;
}

Но когда я попыталься создать приложение Windows Forms и в процедуру Form1_Activated внес этот код (естественно выводом значение в EditBox) ругается на __cpuid
error C3861: __cpuid: идентификатор не найден

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
private: System::Void Form1_Activated(System::Object^  sender, System::EventArgs^  e) {
    int argc;
    char CPUString[0x20];
    char CPUBrandString[0x40];
    int CPUInfo[4] = {-1};
    int nSteppingID = 0;
    int nModel = 0;
    int nFamily = 0;
    int nProcessorType = 0;
    int nExtendedmodel = 0;
    int nExtendedfamily = 0;
    int nBrandIndex = 0;
    int nCLFLUSHcachelinesize = 0;
    int nAPICPhysicalID = 0;
    int nFeatureInfo = 0;
    int nCacheLineSize = 0;
    int nL2Associativity = 0;
    int nCacheSizeK = 0;
    int nRet = 0;
    unsigned    nIds, nExIds, i;
 
 
    // __cpuid with an InfoType argument of 0 returns the number of
    // valid Ids in CPUInfo[0] and the CPU identification string in
    // the other three array elements. The CPU identification string is
    // not in linear order. The code below arranges the information 
    // in a human readable form.
    __cpuid(CPUInfo, 0);
    nIds = CPUInfo[0];
    memset(CPUString, 0, sizeof(CPUString));
    *((int*)CPUString) = CPUInfo[1];
    *((int*)(CPUString+4)) = CPUInfo[3];
    *((int*)(CPUString+8)) = CPUInfo[2];
 
    // Get the information associated with each valid Id
    for (i=0; i<=nIds; ++i)
    {
        __cpuid(CPUInfo, i);
 
 
        // Interpret CPU feature information.
        if  (i == 1)
        {
            nSteppingID = CPUInfo[0] & 0xf;
            nModel = (CPUInfo[0] >> 4) & 0xf;
            nFamily = (CPUInfo[0] >> 8) & 0xf;
            nProcessorType = (CPUInfo[0] >> 12) & 0x3;
            nExtendedmodel = (CPUInfo[0] >> 16) & 0xf;
            nExtendedfamily = (CPUInfo[0] >> 20) & 0xff;
            nBrandIndex = CPUInfo[1] & 0xff;
            nCLFLUSHcachelinesize = ((CPUInfo[1] >> 8) & 0xff) * 8;
            nAPICPhysicalID = (CPUInfo[1] >> 24) & 0xff;
            nFeatureInfo = CPUInfo[3];
        }
    }
 
    // Calling __cpuid with 0x80000000 as the InfoType argument
    // gets the number of valid extended IDs.
    __cpuid(CPUInfo, 0x80000000);
    nExIds = CPUInfo[0];
    memset(CPUBrandString, 0, sizeof(CPUBrandString));
 
    // Get the information associated with each extended ID.
    for (i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);
 
 
        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
            memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000003)
            memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000004)
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000006)
        {
            nCacheLineSize = CPUInfo[2] & 0xff;
            nL2Associativity = (CPUInfo[2] >> 12) & 0xf;
            nCacheSizeK = (CPUInfo[2] >> 16) & 0xffff;
        }
    }
 
    // Display all the information in user-friendly format.
 
 
/*
    if  (nExIds >= 0x80000004)
        textBox1->Text=CPUBrandString.ToString(); */
 
    if  (nExIds >= 0x80000006)
    {
        textBox1->Text=nCacheLineSize.ToString();
        textBox2->Text=nL2Associativity.ToString();
        textBox3->Text=nCacheSizeK.ToString();
    }
 
 
    
    }

В Form1.h подключил слещующие файлы:

C++
1
2
3
4
5
#include <stdio.h>
#include <string.h>
#include <intrin.h>
#include <windows.h>
#include <sstream>

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



0



description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C3861

Compiler Error C3861

06/29/2022

C3861

C3861

0a1eee30-b3db-41b1-b1e5-35949c3924d7

Compiler Error C3861

identifier‘: identifier not found

The compiler was unable to resolve a reference to an identifier, even using argument-dependent lookup.

Remarks

To fix this error, compare use of identifier to the identifier declaration for case and spelling. Verify that scope resolution operators and namespace using directives are used correctly. If the identifier is declared in a header file, verify that the header is included before the identifier is referenced. If the identifier is meant to be externally visible, make sure that it’s declared in any source file that uses it. Also check that the identifier declaration or definition isn’t excluded by conditional compilation directives.

Changes to remove obsolete functions from the C Runtime Library in Visual Studio 2015 can cause C3861. To resolve this error, remove references to these functions or replace them with their secure alternatives, if any. For more information, see Obsolete functions.

If error C3861 appears after project migration from older versions of the compiler, you may have issues related to supported Windows versions. Visual C++ no longer supports targeting Windows 95, Windows 98, Windows ME, Windows NT or Windows 2000. If your WINVER or _WIN32_WINNT macros are assigned to one of these versions of Windows, you must modify the macros. For more information, see Modifying WINVER and _WIN32_WINNT.

Examples

Undefined identifier

The following sample generates C3861 because the identifier isn’t defined.

// C3861.cpp
void f2(){}
int main() {
   f();    // C3861
   f2();   // OK
}

Identifier not in scope

The following sample generates C3861, because an identifier is only visible in the file scope of its definition, unless it’s declared in other source files that use it.

Source file C3861_a1.cpp:

// C3861_a1.cpp
// Compile with: cl /EHsc /W4 C3861_a1.cpp C3861_a2.cpp
#include <iostream>
// Uncomment the following line to fix:
// int f();  // declaration makes external function visible
int main() {
   std::cout << f() << std::endl;    // C3861
}

Source file C3861_a2.cpp:

// C3861_a2.cpp
int f() {  // declared and defined here
   return 42;
}

Namespace qualification required

Exception classes in the C++ Standard Library require the std namespace.

// C3861_b.cpp
// compile with: /EHsc
#include <iostream>
int main() {
   try {
      throw exception("Exception");   // C3861
      // try the following line instead
      // throw std::exception("Exception");
   }
   catch (...) {
      std::cout << "caught an exception" << std::endl;
   }
}

Obsolete function called

Obsolete functions have been removed from the CRT library.

// C3861_c.cpp
#include <stdio.h>
int main() {
   char line[21]; // room for 20 chars + ''
   gets( line );  // C3861
   // Use gets_s instead.
   printf( "The line entered was: %sn", line );
}

ADL and friend functions

The following sample generates C3767 because the compiler can’t use argument dependent lookup for FriendFunc:

namespace N {
   class C {
      friend void FriendFunc() {}
      friend void AnotherFriendFunc(C* c) {}
   };
}

int main() {
   using namespace N;
   FriendFunc();   // C3861 error
   C* pC = new C();
   AnotherFriendFunc(pC);   // found via argument-dependent lookup
}

To fix the error, declare the friend in class scope and define it in namespace scope:

class MyClass {
   int m_private;
   friend void func();
};

void func() {
   MyClass s;
   s.m_private = 0;
}

int main() {
   func();
}
description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C3861

Compiler Error C3861

06/29/2022

C3861

C3861

0a1eee30-b3db-41b1-b1e5-35949c3924d7

Compiler Error C3861

identifier‘: identifier not found

The compiler was unable to resolve a reference to an identifier, even using argument-dependent lookup.

Remarks

To fix this error, compare use of identifier to the identifier declaration for case and spelling. Verify that scope resolution operators and namespace using directives are used correctly. If the identifier is declared in a header file, verify that the header is included before the identifier is referenced. If the identifier is meant to be externally visible, make sure that it’s declared in any source file that uses it. Also check that the identifier declaration or definition isn’t excluded by conditional compilation directives.

Changes to remove obsolete functions from the C Runtime Library in Visual Studio 2015 can cause C3861. To resolve this error, remove references to these functions or replace them with their secure alternatives, if any. For more information, see Obsolete functions.

If error C3861 appears after project migration from older versions of the compiler, you may have issues related to supported Windows versions. Visual C++ no longer supports targeting Windows 95, Windows 98, Windows ME, Windows NT or Windows 2000. If your WINVER or _WIN32_WINNT macros are assigned to one of these versions of Windows, you must modify the macros. For more information, see Modifying WINVER and _WIN32_WINNT.

Examples

Undefined identifier

The following sample generates C3861 because the identifier isn’t defined.

// C3861.cpp
void f2(){}
int main() {
   f();    // C3861
   f2();   // OK
}

Identifier not in scope

The following sample generates C3861, because an identifier is only visible in the file scope of its definition, unless it’s declared in other source files that use it.

Source file C3861_a1.cpp:

// C3861_a1.cpp
// Compile with: cl /EHsc /W4 C3861_a1.cpp C3861_a2.cpp
#include <iostream>
// Uncomment the following line to fix:
// int f();  // declaration makes external function visible
int main() {
   std::cout << f() << std::endl;    // C3861
}

Source file C3861_a2.cpp:

// C3861_a2.cpp
int f() {  // declared and defined here
   return 42;
}

Namespace qualification required

Exception classes in the C++ Standard Library require the std namespace.

// C3861_b.cpp
// compile with: /EHsc
#include <iostream>
int main() {
   try {
      throw exception("Exception");   // C3861
      // try the following line instead
      // throw std::exception("Exception");
   }
   catch (...) {
      std::cout << "caught an exception" << std::endl;
   }
}

Obsolete function called

Obsolete functions have been removed from the CRT library.

// C3861_c.cpp
#include <stdio.h>
int main() {
   char line[21]; // room for 20 chars + ''
   gets( line );  // C3861
   // Use gets_s instead.
   printf( "The line entered was: %sn", line );
}

ADL and friend functions

The following sample generates C3767 because the compiler can’t use argument dependent lookup for FriendFunc:

namespace N {
   class C {
      friend void FriendFunc() {}
      friend void AnotherFriendFunc(C* c) {}
   };
}

int main() {
   using namespace N;
   FriendFunc();   // C3861 error
   C* pC = new C();
   AnotherFriendFunc(pC);   // found via argument-dependent lookup
}

To fix the error, declare the friend in class scope and define it in namespace scope:

class MyClass {
   int m_private;
   friend void func();
};

void func() {
   MyClass s;
   s.m_private = 0;
}

int main() {
   func();
}

Содержание

  1. Ошибка компилятора C3861
  2. Remarks
  3. Примеры
  4. Неопределенный идентификатор
  5. Идентификатор не в области
  6. Требуется квалификация пространства имен
  7. Устаревшая функция, вызываемая
  8. ADL и дружественные функции
  9. ‘random’: ошибка не найден идентификатор
  10. 2 ответы

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

Компилятору не удалось разрешить ссылку на идентификатор, даже используя поиск, зависящий от аргументов.

Чтобы устранить эту ошибку, сравните использование идентификатора с объявлением идентификатора для регистра и орфографии. Убедитесь, что операторы разрешения области и директивы пространства имен using используются правильно. Если идентификатор объявлен в файле заголовка, убедитесь, что заголовок включен до ссылки на идентификатор. Если идентификатор должен быть видимым извне, убедитесь, что он объявлен в любом исходном файле, который его использует. Кроме того, убедитесь, что объявление или определение идентификатора не исключается директивами условной компиляции.

Изменения для удаления устаревших функций из библиотеки среды выполнения C в Visual Studio 2015 могут вызвать C3861. Чтобы устранить эту ошибку, удалите ссылки на эти функции или замените их безопасными альтернативами, если таковые есть. Дополнительные сведения см. в разделе «Устаревшие функции».

Если ошибка C3861 появляется после миграции проекта из более старых версий компилятора, могут возникнуть проблемы, связанные с поддерживаемыми версиями Windows. Visual C++ больше не поддерживает создание программ для Windows 95, Windows 98, Windows ME, Windows NT и Windows 2000. Если макросы WINVER _WIN32_WINNT назначены одной из этих версий Windows, необходимо изменить макросы. Дополнительные сведения см. в разделе «Изменение WINVER и _WIN32_WINNT «.

Примеры

Неопределенный идентификатор

В следующем примере возникает ошибка C3861, так как идентификатор не определен.

Идентификатор не в области

Следующий пример приводит к возникновению ошибки C3861, так как идентификатор виден только в области его определения файла, если он не объявлен в других исходных файлах, использующих его.

Исходный файл C3861_a1.cpp :

Исходный файл C3861_a2.cpp :

Требуется квалификация пространства имен

Для классов исключений в стандартной библиотеке C++ требуется std пространство имен.

Устаревшая функция, вызываемая

Устаревшие функции удалены из библиотеки CRT.

ADL и дружественные функции

Следующий пример приводит к возникновению ошибки C3767, так как компилятор не может использовать поиск, зависящий от FriendFunc аргументов:

Чтобы устранить ошибку, объявите друга в области класса и определите его в области пространства имен:

Источник

‘random’: ошибка не найден идентификатор

Я пытаюсь перенести код, написанный для UNIX, в Visual Studio и получаю следующие ошибки

Код длинный, но я уже включен math.h но я все еще получаю эти ошибки. Возможно, эти функции доступны только для UNIX! Если да, то что я могу сделать?

Вот модифицированный образец моего кода (строки, которые дают мне ошибки);

О, я имею в виду, что не пишите имена функций ВСЕМИ ЗАГЛАВНЫМИ буквами. — Sufian Latif

2 ответы

random -> rand (Не забудьте # include для этого)

И напишите initstate перед основным или сделать предварительное заявление.

Как мне написать initstate перед основным или сделать предварительное заявление? initstate вызывается в другой функции (которая называется моей основной) — Ророноа-Зоро

Для прямого объявления поместите подпись функции в начало кода. — Суфиан Латиф

Извините, если это прозвучало банально. Но у меня нет определения initstate . Разве это не должно быть похоже random ? — Ророноа-Зоро

Тогда как ты звонишь initstate ? — Суфиан Латиф

Используйте функции srand() и rand() от stdlib.h с целью. — Суфиан Латиф

Включите stdlib.h и используйте функцию rand ().

Также функции имеют имена в нижнем регистре cos, log, sqrt.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c++ visual-studio-2010 random or задайте свой вопрос.

Источник

I have a problem with my code. Unfortunately, when compiling I get these errors all the time. What can this be caused by and how to fix it?

error C3861: ‘print’: identifier not found

My code:

main.cpp

#include "pojazdy.h"
#include <iostream>

using namespace std;

int main()
{
    Pojazdy** poj;
    int size{ 0 }, index{ 0 };
    Petla(poj, size);

    print(poj, size);

    wyrejestruj(poj,size,0);
    print(poj, size);
    wyrejestruj(poj,size);

    return 0;
}

pojazdy.h

#ifndef pojazdy_h
#define pojazdy_h

#include <iostream>
#include <cstdlib>

using namespace std;

class Pojazdy
{
public:
    string typ;
    string marka;
    string model;
    string z_dod;
    int ilosc;
    int cena;

    void dodaj();
    void d_pojazd(Pojazdy**& pojazdy, int& size);
    void wyrejestruj(Pojazdy**& pojazdy, int& size, int index);
    void print(Pojazdy** pojazdy, int size);
    void Petla(Pojazdy**& p, int& size);

    //void wyswietl();
    int get_ilosc() { return ilosc; }
    string get_typ() { return typ; }
    string get_marka() { return marka; }
    string get_model() { return model; }
    int get_cena() { return cena; }
    void set_ilosc(int x);
};

#endif

pojazdy.cpp

#include "pojazdy.h"

#include <iostream>

using namespace std;

void Pojazdy::set_ilosc(int x) { ilosc = x; }

void Pojazdy::dodaj()
{
    cout << "DODAWANIE POJAZDU..." << endl;
    cout << "Podaj typ pojazdu:";
    cin >> typ;

    cout << "Podaj marke pojazdu: ";
    cin >> marka;

    cout << "Podaj model pojazdu: ";
    cin >> model;

    cout << "Dodaj cene pojazdu: ";
    cin >> cena;
}

void Petla(Pojazdy**& p, int& size) {
    char z_dod;// = 'N';
    do {
        d_pojazd(p, size); //odpowiada za dodawnie
        p[size - 1]->dodaj();
        cout << "Czy chcesz zakonczyc dodawanie? Jesli tak, wcisnij Y/N: ";
        cin >> z_dod;

    } while (z_dod == 'N' || z_dod == 'n');//while (p[size]->z_dod == "N" ||p[size]->z_dod == "n");
}

void print(Pojazdy** pojazdy, int size) {
    std::cout << "====================================" << std::endl;
    for (int i{ 0 }; i < size; i++)
        std::cout << "Typ: " << pojazdy[i]->get_typ() << " Marka: " << pojazdy[i]->get_marka() << " Model: " << pojazdy[i]->get_model() << " Cena: " << pojazdy[i]->get_model() << std::endl;
}

void wyrejestruj(Pojazdy**& pojazdy, int& size) {
    for (size_t i{ 0 }; i < size; i++)
        delete pojazdy[i];
    delete[] pojazdy;
    size = 0;
    pojazdy = NULL;
}

void wyrejestruj(Pojazdy**& pojazdy, int& size, int index) {
    if (index < size) {
        Pojazdy** temp = new Pojazdy * [size - 1];
        short int j{ -1 };
        for (size_t i{ 0 }; i < size; i++) {
            if (i != index) {
                j++;
                temp[j] = pojazdy[i];
            }
        }
        delete[] pojazdy;
        --size;
        pojazdy = temp;
    }
    else
        std::cout << "Pamiec zwolniona!" << std::endl;
}

void d_pojazd(Pojazdy**& pojazdy, int& size) {
    Pojazdy** temp = new Pojazdy * [size + 1];
    if (size == 0)
        temp[size] = new Pojazdy;
    else {
        for (int i{ 0 }; i < size; i++)
            temp[i] = pojazdy[i];
        delete[] pojazdy;

        temp[size] = new Pojazdy;
    }
    ++size;
    pojazdy = temp;
}

I used #ifndef, #define, #endif and #pragma once, but none of them work. I will be really grateful for every code, I am already tired of this second hour. And forgive the non-English variables and function names for them — it’s university code, so I didn’t feel the need.

На чтение 6 мин. Просмотров 95 Опубликовано 15.12.2019

«идентификатор«: идентификатор не найден ‘identifier‘: identifier not found

Компилятору не удалось разрешить ссылку на идентификатор даже при поиске с зависимостью от аргументов. The compiler was not able to resolve a reference to an identifier, even using argument-dependent lookup.

Содержание

  1. Примечания Remarks
  2. Примеры Examples
  3. Неопределенный идентификатор Undefined identifier
  4. Идентификатор не находится в области Identifier not in scope
  5. Требуется квалификации пространства имен Namespace qualification required
  6. Устаревшие функции с именем Obsolete function called
  7. ADL и дружественные функции ADL and friend functions
  8. Решение
  9. Другие решения
  10. 2 ответа 2

Чтобы устранить эту ошибку, сравните использование идентификатор на написание и регистр объявления идентификатора. To fix this error, compare use of identifier to the identifier declaration for case and spelling. Убедитесь, что операторов разрешения области и пространство имен директив using используются правильно. Verify that scope resolution operators and namespace using directives are used correctly. Если идентификатор объявлен в файле заголовка, убедитесь, что заголовок включен до ссылки на идентификатор. If the identifier is declared in a header file, verify that the header is included before the identifier is referenced. Если идентификатор должен быть видимый извне, убедитесь, что он объявлен в все файлы исходного кода, который его использует. If the identifier is meant to be externally visible, make sure that it is declared in any source file that uses it. Также проверьте, что идентификатор объявления или определения не исключен с директивы условной компиляции. Also check that the identifier declaration or definition is not excluded by conditional compilation directives.

Изменения, чтобы удалить устаревшие функции из библиотеки времени выполнения C в Visual Studio 2015 может привести к C3861. Changes to remove obsolete functions from the C Runtime Library in Visual Studio 2015 can cause C3861. Чтобы устранить эту ошибку, удалите ссылки на эти функции или замените их безопасных альтернатив, если таковые имеются. To resolve this error, remove references to these functions or replace them with their secure alternatives, if any. Дополнительные сведения см. в разделе устаревшие функции. For more information, see Obsolete Functions.

При появлении ошибки C3861 после миграции проекта из более старой версии компилятора, возможно, возникли проблемы, связанные с поддерживаемыми версиями Windows. If error C3861 appears after project migration from older versions of the compiler, you may have issues related to supported Windows versions. Visual C++ больше не поддерживает создание программ для Windows 95, Windows 98, Windows ME, Windows NT и Windows 2000. Visual C++ no longer supports targeting Windows 95, Windows 98, Windows ME, Windows NT or Windows 2000. Если ваши макросы WINVER или _WIN32_WINNT предназначены для одной из этих версий Windows, необходимо изменить такие макросы. If your WINVER or _WIN32_WINNT macros are assigned to one of these versions of Windows, you must modify the macros. Дополнительные сведения см. в разделе изменение WINVER и _WIN32_WINNT. For more information, see Modifying WINVER and _WIN32_WINNT.

Примеры Examples

Неопределенный идентификатор Undefined identifier

Следующий пример приводит к возникновению ошибки C3861, так как идентификатор не определен. The following sample generates C3861 because the identifier is not defined.

Идентификатор не находится в области Identifier not in scope

Следующий пример приводит к возникновению ошибки C3861, так как идентификатор отображается в области видимости файла его определения, только в том случае, если она не объявлена в других исходных файлах, которые ее используют. The following sample generates C3861 because an identifier is only visible in the file scope of its definition, unless it is declared in other source files that use it.

Требуется квалификации пространства имен Namespace qualification required

Классы исключений в стандартной библиотеке C++ требует std пространства имен. Exception classes in the C++ Standard Library require the std namespace.

Устаревшие функции с именем Obsolete function called

Устаревшие функции были удалены из библиотеки CRT. Obsolete functions have been removed from the CRT library.

ADL и дружественные функции ADL and friend functions

В следующем примере возникает C3767, так как компилятор не может использовать поиск по аргументам для FriendFunc : The following sample generates C3767 because the compiler cannot use argument dependent lookup for FriendFunc :

Чтобы устранить эту ошибку, объявите friend в области видимости класса и определите его в области видимости пространства имен: To fix the error, declare the friend in class scope and define it in namespace scope:

У меня есть файл «HSlider.h», он использует «Draw.h», где я определил свои функции для их использования.
Но компилятор говорит, что я не определил их (идентификатор не найден). Я искал на форумах похожую ошибку, но это не помогло.

Я работаю в VS 2015 Communty.

ПРИМЕР ОШИБКИ:
Ошибка C3861 DrawGUIBox: идентификатор не найден
Try2 c: users lel Documents visual studio 2015 projects try2 try2 hslider.h 50
,

HSlider.h

Draw.h

Решение

Проблема не в вашем исходном коде. Проблема в том, что ваш файл решения Visual Studio (в указанной вами ссылке) поврежден. В файле решения есть ссылки на проект под названием Try2, но этот проект не существует в решении.

Чтобы это исправить, сделайте следующее.

Откройте файл Help.sln с помощью notepad ++, и вы увидите строку

Это означает, что должен быть подпроект под названием Try2, но он не существует. В вашем архиве субпроект фактически называется «Помощь». Итак, измените строку на:

После этого просмотрите папки x64 в своем решении и удалите все оставшиеся файлы, относящиеся к Try2.

ИЛИ, создайте новое пустое решение и скопируйте исходные файлы .cpp и .h (только) по одному в новое решение.

(Существует также отдельная проблема, когда отсутствует файл Offsets.h, но я не могу с этим помочь.)

Другие решения

Я нашел ответ сам.
Проблема была в круговом включении.
И это произошло потому, что я определил свои классы в файле заголовка вместо файла .cpp.
После этого и правильного перемещения заголовков я исправил это за считанные минуты.

Использую библиотеку math.h и в ней для нахождения кубического корня есть функция cbrt(); Только вот при компиляции Visual Studio говорит: error C3861: cbrt: идентификатор не найден.

Как решать проблему?

2 ответа 2

Правильно он споткнулся. Потому что эта функция находиться в другом заголовчном файле — amp_math.h (пруф).

Не знаю, с чем связано отсутствие этой функции, но попробуйте вот так:

Вообще cbrt есть в С99 и в C++TR1, который, кажется, как раз вошел в C++11. Ну а упрекнуть vc++ в хорошей поддержке этого стандарта до сих пор довольно трудно

  • Remove From My Forums
  • Question

  • I am trying to determine whether a specific string is included in a list by using «find» in c++. However, whenever I try to compile the following code, the compiler returns «error C3861: ‘find’: identifier not found.» I am unsure of where I am going wrong.
    I would appreciate if someone could either point out why «find» will not work as written or provide and alternative method for determining how to determine if a variable is not in a list.

    Thanks

    #include <iostream>
    #include <string>
    
    #include <list>
    
    using namespace std;
    
    int main()
    {
    	string myString[] = {"text1","text2","text3"};
    	list<string> myList(&myString[0],&myString[2]);
    
    	string myInput;
    	cout << "What string do you want to check? ";
    	cin >> myInput;
    
    	if (find(myList.begin(),myList.end(),myInput) != myList.end())
    	{
    		cout << "Not found in list";
    	}
    	return 0;
    }
    

Answers

  • PrestonBR wrote:

    I am trying to determine whether a specific string is included in a  list by using «find» in c++. However, whenever I try to
    compile the following code, the compiler returns «error C3861: ‘find’:  identifier not found.»

    #include <algorithm>


    Igor Tandetnik

    • Marked as answer by

      Sunday, January 1, 2012 5:09 PM

В консольном приложении __cpuid отлично вызывается

Код:

#include <stdio.h>
#include <string.h>
#include <intrin.h>
#include <conio.h>
#include <windows.h>

 
 
int main()
{
        int argc;
    char CPUString[0x20];
    char CPUBrandString[0x40];
    int CPUInfo[4] = {-1};
    int nSteppingID = 0;
    int nModel = 0;
    int nFamily = 0;
    int nProcessorType = 0;
    int nExtendedmodel = 0;
    int nExtendedfamily = 0;
    int nBrandIndex = 0;
    int nCLFLUSHcachelinesize = 0;
    int nAPICPhysicalID = 0;
    int nFeatureInfo = 0;
    int nCacheLineSize = 0;
    int nL2Associativity = 0;
    int nCacheSizeK = 0;
    int nRet = 0;
    unsigned    nIds, nExIds, i;

 
 
    // __cpuid with an InfoType argument of 0 returns the number of
    // valid Ids in CPUInfo[0] and the CPU identification string in
    // the other three array elements. The CPU identification string is
    // not in linear order. The code below arranges the information
    // in a human readable form.
    __cpuid(CPUInfo, 0);
    nIds = CPUInfo[0];
    memset(CPUString, 0, sizeof(CPUString));
    *((int*)CPUString) = CPUInfo[1];
    *((int*)(CPUString+4)) = CPUInfo[3];
    *((int*)(CPUString+8)) = CPUInfo[2];

 
    // Get the information associated with each valid Id
    for (i=0; i<=nIds; ++i)
    {
        __cpuid(CPUInfo, i);

 
 
        // Interpret CPU feature information.
        if  (i == 1)
        {
            nSteppingID = CPUInfo[0] & 0xf;
            nModel = (CPUInfo[0] >> 4) & 0xf;
            nFamily = (CPUInfo[0] >> 8) & 0xf;
            nProcessorType = (CPUInfo[0] >> 12) & 0x3;
            nExtendedmodel = (CPUInfo[0] >> 16) & 0xf;
            nExtendedfamily = (CPUInfo[0] >> 20) & 0xff;
            nBrandIndex = CPUInfo[1] & 0xff;
            nCLFLUSHcachelinesize = ((CPUInfo[1] >> 8) & 0xff) * 8;
            nAPICPhysicalID = (CPUInfo[1] >> 24) & 0xff;
            nFeatureInfo = CPUInfo[3];
        }
    }

 
    // Calling __cpuid with 0x80000000 as the InfoType argument
    // gets the number of valid extended IDs.
    __cpuid(CPUInfo, 0x80000000);
    nExIds = CPUInfo[0];
    memset(CPUBrandString, 0, sizeof(CPUBrandString));

 
    // Get the information associated with each extended ID.
    for (i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);

 
 
        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
            memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000003)
            memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000004)
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000006)
        {
            nCacheLineSize = CPUInfo[2] & 0xff;
            nL2Associativity = (CPUInfo[2] >> 12) & 0xf;
            nCacheSizeK = (CPUInfo[2] >> 16) & 0xffff;
        }
    }

 
    // Display all the information in user-friendly format.

 
    printf_s(«nnCPU String: %sn», CPUString);

 
 
    if  (nExIds >= 0x80000004)
        printf_s(«nCPU Brand String: %sn», CPUBrandString);

 
    if  (nExIds >= 0x80000006)
    {
        printf_s(«Cache Line Size = %dn», nCacheLineSize);
        printf_s(«L2 Associativity = %dn», nL2Associativity);
        printf_s(«Cache Size = %dKn», nCacheSizeK);
    }

 
        if (IsProcessorFeaturePresent(PF_3DNOW_INSTRUCTIONS_AVAILABLE))  
                printf_s(«nПоддержует технологию»);

   
 
 
getch();
return  nRet;
}

Но когда я попыталься создать приложение Windows Forms и в процедуру Form1_Activated внес этот код (естественно выводом значение в EditBox) ругается на __cpuid
error C3861: __cpuid: идентификатор не найден

Код:

private: System::Void Form1_Activated(System::Object^  sender, System::EventArgs^  e) {
        int argc;
        char CPUString[0x20];
    char CPUBrandString[0x40];
    int CPUInfo[4] = {-1};
    int nSteppingID = 0;
    int nModel = 0;
    int nFamily = 0;
    int nProcessorType = 0;
    int nExtendedmodel = 0;
    int nExtendedfamily = 0;
    int nBrandIndex = 0;
    int nCLFLUSHcachelinesize = 0;
    int nAPICPhysicalID = 0;
    int nFeatureInfo = 0;
    int nCacheLineSize = 0;
    int nL2Associativity = 0;
    int nCacheSizeK = 0;
    int nRet = 0;
    unsigned    nIds, nExIds, i;

 
 
    // __cpuid with an InfoType argument of 0 returns the number of
    // valid Ids in CPUInfo[0] and the CPU identification string in
    // the other three array elements. The CPU identification string is
    // not in linear order. The code below arranges the information
    // in a human readable form.
    __cpuid(CPUInfo, 0);
    nIds = CPUInfo[0];
    memset(CPUString, 0, sizeof(CPUString));
    *((int*)CPUString) = CPUInfo[1];
    *((int*)(CPUString+4)) = CPUInfo[3];
    *((int*)(CPUString+8)) = CPUInfo[2];

 
    // Get the information associated with each valid Id
    for (i=0; i<=nIds; ++i)
    {
        __cpuid(CPUInfo, i);

 
 
        // Interpret CPU feature information.
        if  (i == 1)
        {
            nSteppingID = CPUInfo[0] & 0xf;
            nModel = (CPUInfo[0] >> 4) & 0xf;
            nFamily = (CPUInfo[0] >> 8) & 0xf;
            nProcessorType = (CPUInfo[0] >> 12) & 0x3;
            nExtendedmodel = (CPUInfo[0] >> 16) & 0xf;
            nExtendedfamily = (CPUInfo[0] >> 20) & 0xff;
            nBrandIndex = CPUInfo[1] & 0xff;
            nCLFLUSHcachelinesize = ((CPUInfo[1] >> 8) & 0xff) * 8;
            nAPICPhysicalID = (CPUInfo[1] >> 24) & 0xff;
            nFeatureInfo = CPUInfo[3];
        }
    }

 
    // Calling __cpuid with 0x80000000 as the InfoType argument
    // gets the number of valid extended IDs.
    __cpuid(CPUInfo, 0x80000000);
    nExIds = CPUInfo[0];
    memset(CPUBrandString, 0, sizeof(CPUBrandString));

 
    // Get the information associated with each extended ID.
    for (i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);

 
 
        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
            memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000003)
            memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000004)
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        else if  (i == 0x80000006)
        {
            nCacheLineSize = CPUInfo[2] & 0xff;
            nL2Associativity = (CPUInfo[2] >> 12) & 0xf;
            nCacheSizeK = (CPUInfo[2] >> 16) & 0xffff;
        }
    }

 
    // Display all the information in user-friendly format.

 
 
/*
    if  (nExIds >= 0x80000004)
                textBox1->Text=CPUBrandString.ToString(); */

 
    if  (nExIds >= 0x80000006)
    {
                textBox1->Text=nCacheLineSize.ToString();
                textBox2->Text=nL2Associativity.ToString();
                textBox3->Text=nCacheSizeK.ToString();
    }

 
 
   
    }

В Form1.h подключил слещующие файлы:

Код:

#include <stdio.h>
#include <string.h>
#include <intrin.h>
#include <windows.h>
#include <sstream>

На чтение 2 мин Обновлено 17.01.2023

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

Компилятору не удалось разрешить ссылку на идентификатор, даже используя поиск, зависящий от аргументов.

Remarks

Чтобы устранить эту ошибку, сравните использование идентификатора с объявлением идентификатора для регистра и орфографии. Убедитесь, что операторы разрешения области и директивы пространства имен using используются правильно. Если идентификатор объявлен в файле заголовка, убедитесь, что заголовок включен до ссылки на идентификатор. Если идентификатор должен быть видимым извне, убедитесь, что он объявлен в любом исходном файле, который его использует. Кроме того, убедитесь, что объявление или определение идентификатора не исключается директивами условной компиляции.

Изменения для удаления устаревших функций из библиотеки среды выполнения C в Visual Studio 2015 могут вызвать C3861. Чтобы устранить эту ошибку, удалите ссылки на эти функции или замените их безопасными альтернативами, если таковые есть. Дополнительные сведения см. в разделе «Устаревшие функции».

Если ошибка C3861 появляется после миграции проекта из более старых версий компилятора, могут возникнуть проблемы, связанные с поддерживаемыми версиями Windows. Visual C++ больше не поддерживает создание программ для Windows 95, Windows 98, Windows ME, Windows NT и Windows 2000. Если макросы WINVER _WIN32_WINNT назначены одной из этих версий Windows, необходимо изменить макросы. Дополнительные сведения см. в разделе «Изменение WINVER и _WIN32_WINNT «.

Примеры

Неопределенный идентификатор

В следующем примере возникает ошибка C3861, так как идентификатор не определен.

Идентификатор не в области

Следующий пример приводит к возникновению ошибки C3861, так как идентификатор виден только в области его определения файла, если он не объявлен в других исходных файлах, использующих его.

Исходный файл C3861_a1.cpp :

Исходный файл C3861_a2.cpp :

Требуется квалификация пространства имен

Для классов исключений в стандартной библиотеке C++ требуется std пространство имен.

Устаревшая функция, вызываемая

Устаревшие функции удалены из библиотеки CRT.

ADL и дружественные функции

Следующий пример приводит к возникновению ошибки C3767, так как компилятор не может использовать поиск, зависящий от FriendFunc аргументов:

Чтобы устранить ошибку, объявите друга в области класса и определите его в области пространства имен:

Источник

Понравилась статья? Поделить с друзьями:
  • Error c3859 failed to create virtual memory for pch
  • Error c3646 noexcept неизвестный спецификатор переопределения
  • Error c36 mark detect
  • Error c3493 cannot be implicitly captured because no default capture mode has been specified
  • Error c2976 std vector слишком мало аргументов шаблон