Ошибка c2731 main функция не может быть перегружена

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2731

Compiler Error C2731

11/04/2016

C2731

C2731

9b563999-febd-4582-9147-f355083c091e

Compiler Error C2731

‘identifier’ : function cannot be overloaded

The functions main, WinMain, DllMain, and LibMain cannot be overloaded.

The following sample generates C2731:

// C2731.cpp
extern "C" void WinMain(int, char *, char *);
void WinMain(int, short, char *, char*);   // C2731

Thanks everyone, I finally found the real culprit, it’s a typo, I use LPSTR lpCmdLine instead of LPTSTR lpCmdLine. The real mystery is why it compiled at all under VC6 — it did use wWinMain, but somehow it was OK for lpCmdLine to be char * instead of WCHAR *.

Now I changed it to:

int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE hPrevInstance,
                       LPTSTR    lpCmdLine,
                       int       nCmdShow)

And it works under VS2008 too.

Edit: I successfully compiled and even ran the program with this function definition under VC6:

int APIENTRY wWinMain(int *hInstance, float hPrevInstance, int *lpCmdLine, float nCmdShow)
{
    MessageBox(0,L"Running.",0,0);
    return 0;
}

Interestingly, replacing float nCmdShow to double nCmdShow does give a linker error, I assume because float is 32-bits but double is not.

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
#include "Main.h"
 
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, char* lpCmdLine, LPCTSTR nCmdShow, LPSTR WindowName, int WindowWidth, int WindowHeight)
{
    g_hInstance = GetModuleHandle(NULL);
 
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);        //Размер структуры
    wc.style = CS_HREDRAW | CS_VREDRAW;      //Стили класса окна
    wc.lpfnWndProc = WndProc;              //Функция обработки сообщений
    wc.cbClsExtra = 0;                //Количество выделяемой памяти при создании приложения
    wc.cbWndExtra = 0;                //Количество выделяемой памяти при создании приложения
    wc.hInstance = g_hInstance;            //Дескриптор приложения
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);  //Загружаем стандартную иконку
    wc.hCursor = LoadCursor(0, IDC_ARROW);      //Загружаем стандартный курсор
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);//Окно будет закрашено в белый цвет
    wc.lpszMenuName = 0;                //Не используем меню
    wc.lpszClassName = "Lost Days";            //Названия класса
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);  //Загружаем стандартную иконку
 
    if (!RegisterClassEx(&wc))                //Регистрируем класс в Windows
    {
        Shutdown();                    //Освобождаем память
        MessageBox(NULL, "Can`t register window class", "Error", MB_OK | MB_ICONERROR); //Выводим сообщение
        return 0;                    //Завершаем работу приложения
    }
 
    g_hWnd = CreateWindowEx(              //Создаем окно
        WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,        //Расширенный стиль окна
        "Lost Days",                    //Названия класса окна
        WindowName,
        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,//Стиль окна
        0,                      //Позиция окна по оси Х
        0,                      //Позиция окна по оси У
        WindowWidth,                //Ширина окна
        WindowHeight,              //Высота окна
        NULL,                    //Это наше главное окно
        NULL,                    //Нету меню
        g_hInstance,                //Дескриптор приложения
        NULL);                    //Дополнительный настроек не используем
 
    if (g_hWnd == NULL)                //Если не создали окно
    {
        Shutdown();
        MessageBox(NULL, "Can`t create window", "Error", MB_OK | MB_ICONERROR);//Выводим сообщение
        return 0;                  //Завершаем работу приложения
    }
 
    if (!InitDirect3D(D3DFMT_R5G6B5, D3DFMT_D16, WindowWidth, WindowHeight))    //Если не смогли инициализировать Direct3D
    {
        Shutdown();
        MessageBox(NULL, "Can`t create direct3d", "Error", MB_OK | MB_ICONERROR);//Выводим сообщение
        return 0;                  //Завершаем работу приложения
    }
 
    ShowWindow(g_hWnd, SW_SHOW);            //Отображаем окно  
    UpdateWindow(g_hWnd);              //Обновляем окно
    SetFocus(g_hWnd);                //Устанавливаем фокус на наше окно
    SetForegroundWindow(g_hWnd);          //Устанавливаем приоритет окна выше среднего
 
    MSG msg;
    ZeroMemory(&msg, sizeof(msg));
 
    while (g_bApplicationState)            //Начинаем бесконечный цикл обработки сообщений
    {
        if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))//Получаем сообщения
        {
            TranslateMessage(&msg);          //Обрабатываем сообщения
            DispatchMessage(&msg);          //Обрабатываем сообщения
        }
        else
            DrawFrame();              //Если сообщений нету рисуем кадры
    }
 
    Shutdown();                    //Освобождаем память
    return 0;                    //Завершаем работу приложения
}

// Include the Windows header file that’s needed for all Windows applications

#include <windows.h>
#include <string.h>
#include <string>
#include <tchar.h>
#include <stdlib.h>
#include <list>
#include <iostream>
HINSTANCE hInst; // global handle to hold the application instance
HWND wndHandle; // global variable to hold the window handle
// make class name into a global variable
TCHAR szClassName[ ] = _T(«WindowsApp»);

// forward declarations
bool initWindow( HINSTANCE hInstance );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
// This is winmain, the main entry point for Windows applications
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow )
{
// Initialize the window
if ( !initWindow( hInstance ) )
return false;
// main message loop:
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message!=WM_QUIT )
{
// Check the message queue
while (GetMessage(&msg, wndHandle, 0, 0) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return (int) msg.wParam;
}

// bool initWindow( HINSTANCE hInstance )
//initWindow registers the window class for the application, creates the window

bool initWindow( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
// Fill in the WNDCLASSEX structure. This describes how the window
// will look to the system
wcex.cbSize = sizeof(WNDCLASSEX); // the size of the structure
wcex.style = CS_HREDRAW | CS_VREDRAW; // the class style
wcex.lpfnWndProc = (WNDPROC)WndProc; // the window procedure callback
wcex.cbClsExtra = 0; // extra bytes to allocate for this class
wcex.cbWndExtra = 0; // extra bytes to allocate for this instance
wcex.hInstance = hInstance; // handle to the application instance
wcex.hIcon = 0; // icon to associate with the application
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);// the default cursor
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // the background color
wcex.lpszMenuName  = NULL; // the resource name for the menu
wcex.lpszClassName = _T(«WindowsApp»); // the class name being created
wcex.hIconSm = 0; // the handle to the small icon

if (!RegisterClassEx(&wcex));
return 0;
// Create the window
wndHandle = CreateWindowEx(
0,
 szClassName,
 _T(«Windows App»),
WS_OVERLAPPEDWINDOW,
// the window class to use
// the title bar text
// the window style

CW_USEDEFAULT, // the starting x coordinate
CW_USEDEFAULT, // the starting y coordinate
640, // the pixel width of the window
480, // the pixel height of the window
NULL, // the parent window; NULL for desktop
NULL, // the menu for the application; NULL for
// none
hInstance, // the handle to the application instance
NULL); // no values passed to the window
// Make sure that the window handle that is created is valid
if (!wndHandle)
return false;
// Display the window on the screen
ShowWindow(wndHandle, SW_SHOW);
UpdateWindow(wndHandle);
return true;
}

// Include the Windows header file that’s needed for all Windows applications

#include <windows.h>
#include <string.h>
#include <string>
#include <tchar.h>
#include <stdlib.h>
#include <list>
#include <iostream>
HINSTANCE hInst; // global handle to hold the application instance
HWND wndHandle; // global variable to hold the window handle
// make class name into a global variable
TCHAR szClassName[ ] = _T(«WindowsApp»);

// forward declarations
bool initWindow( HINSTANCE hInstance );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
// This is winmain, the main entry point for Windows applications
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow )
{
// Initialize the window
if ( !initWindow( hInstance ) )
return false;
// main message loop:
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message!=WM_QUIT )
{
// Check the message queue
while (GetMessage(&msg, wndHandle, 0, 0) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return (int) msg.wParam;
}

// bool initWindow( HINSTANCE hInstance )
//initWindow registers the window class for the application, creates the window

bool initWindow( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
// Fill in the WNDCLASSEX structure. This describes how the window
// will look to the system
wcex.cbSize = sizeof(WNDCLASSEX); // the size of the structure
wcex.style = CS_HREDRAW | CS_VREDRAW; // the class style
wcex.lpfnWndProc = (WNDPROC)WndProc; // the window procedure callback
wcex.cbClsExtra = 0; // extra bytes to allocate for this class
wcex.cbWndExtra = 0; // extra bytes to allocate for this instance
wcex.hInstance = hInstance; // handle to the application instance
wcex.hIcon = 0; // icon to associate with the application
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);// the default cursor
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // the background color
wcex.lpszMenuName  = NULL; // the resource name for the menu
wcex.lpszClassName = _T(«WindowsApp»); // the class name being created
wcex.hIconSm = 0; // the handle to the small icon

if (!RegisterClassEx(&wcex));
return 0;
// Create the window
wndHandle = CreateWindowEx(
0,
 szClassName,
 _T(«Windows App»),
WS_OVERLAPPEDWINDOW,
// the window class to use
// the title bar text
// the window style

CW_USEDEFAULT, // the starting x coordinate
CW_USEDEFAULT, // the starting y coordinate
640, // the pixel width of the window
480, // the pixel height of the window
NULL, // the parent window; NULL for desktop
NULL, // the menu for the application; NULL for
// none
hInstance, // the handle to the application instance
NULL); // no values passed to the window
// Make sure that the window handle that is created is valid
if (!wndHandle)
return false;
// Display the window on the screen
ShowWindow(wndHandle, SW_SHOW);
UpdateWindow(wndHandle);
return true;
}

  1. Mark

    Марк

    Публикаций:

    0

    Регистрация:
    15 сен 2011
    Сообщения:
    304

    Решил создать эту тему т.к. в предыдущей никто не ответил.

    Ругается Visual S – “Функция WinMain не может быть перегружена”

    1. const int EditCtrlID = 12;

    2. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

    3. LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)

    4.         if(LOWORD(wParam)==10000)

    5.             char f[] = {«Name.txt»};

    6.             HANDLE hFile = CreateFileA(

    7.                                         GENERIC_READ | GENERIC_WRITE,

    8.                                         FILE_SHARE_READ | FILE_SHARE_WRITE,

    9.             WriteFile(hFile, st, ARRAYSIZE(st), &dwBytesWritten, NULL);

    10.             return DefWindowProc(hWnd, message, wParam, lParam);

    11. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, INT nCmdShow)

    12. {                                                       < ———————-Вот тут. Функция не может быть перегружена

    13.     wchar_t cname[] = L»Class»;

    14.     wchar_t title[] = L»Заметки. Ver 1.0 Beta»;

    15.     wc.lpfnWndProc = (WNDPROC)WndProc;

    16.     wc.hInstance = hInstance;

    17.     wc.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_APPLICATION);

    18.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);

    19.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);

    20.     wc.lpszClassName = cname;

    21.     if(!RegisterClass(&wc)) return 0;

    22.     HWND hWnd = CreateWindow(

    23.                              WS_MINIMIZEBOX|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME,  

    24.     HWND hWnd_button = CreateWindow(

    25.                                     WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,

    26.     ShowWindow(hWnd, nCmdShow);

    27.     hWnd = CreateWindow(L»edit», L»nnnВаши заметки: «,

    28.                            WS_VISIBLE | WS_CHILD | WS_HSCROLL |WS_VSCROLL|ES_NOHIDESEL|ES_MULTILINE|WS_VISIBLE|WS_BORDER|ES_AUTOVSCROLL|ES_MULTILINE|ES_LEFT,

    29.     ShowWindow(hWnd, nCmdShow);

    30.     while(GetMessage(&msg, NULL,0 ,0))

  2. Sholar

    New Member

    Публикаций:

    0

    Регистрация:
    16 окт 2011
    Сообщения:
    189

    Убери T и попробуй скомпилить.

  3. Blackbeam

    New Member

    Публикаций:

    0

    Регистрация:
    28 дек 2008
    Сообщения:
    965
  4. Mark

    Марк

    Публикаций:

    0

    Регистрация:
    15 сен 2011
    Сообщения:
    304
  5. Mark

    Марк

    Публикаций:

    0

    Регистрация:
    15 сен 2011
    Сообщения:
    304

    Sholar

    Спасибо. Тема закрыта.

  6. K10

    New Member

    Публикаций:

    0

    Регистрация:
    3 окт 2008
    Сообщения:
    1.590
  7. Ezrah

    Member

    Публикаций:

    0

    Регистрация:
    22 мар 2011
    Сообщения:
    412

    K10
    За что?
    Mark
    Несколько замечаний.
    0) Раз используете UNICODE, WinMain должна обзываться wWinMain, и тогда компилироваться будет без исправлений (но, лучше будет исправить тогда LPTSTR на LPWSTR).
    1) Структуру MSG нет смысла объявлять глобальной, т.к. она не используется нигде кроме WinMain. То же касается dwBytesWritten и button.
    2) Макрос ARRAYSIZE возвращает число элементов, а не количество байтов, в то время как в WriteFile нужно передавать именно число байтов. Используйте sizeof().
    3) char f[] = {«Name.txt»}; Тут добавлять не нужно, и вообще строки объявляют так: char f[] = «Name.txt», т.е. без скобок.
    4) Стили WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, WS_MAXIMIZEBOX вместе эквивалентны применению стиля WS_OVERLAPPEDWINDOW, т.о. можно сократить объем текста и сделать текст более наглядным.
    5) Рекомендуется, чтобы все дочерние элементы окна имели стиль WS_CLIPSIBLINGS, это позволяет частично избежать мерцания при изменении размеров главного окна.
    6) Оставлять пустой обработчик WM_PAINT плохая идея, должны быть как минимум BeginPaint/EndPaint, иначе происходит что-то не хорошее (по своему опыту), не помню что.
    7) После завершения работы с файлом его полагается закрыть. CloseHandle в помощь.

  8. K10

    New Member

    Публикаций:

    0

    Регистрация:
    3 окт 2008
    Сообщения:
    1.590

    Ezrah

    Принципиально не желает изучить основы и дублирует темы, нервируя достопочтенную публику.
    Я понимаю, что все с чего то начинали, но никто такие rtfm вопросы на форуме не задавал.

  9. Mark

    Марк

    Публикаций:

    0

    Регистрация:
    15 сен 2011
    Сообщения:
    304
  10. Ezrah

    Member

    Публикаций:

    0

    Регистрация:
    22 мар 2011
    Сообщения:
    412

    K10
    Ну что ж, сложно не согласиться. Будь в дурном расположении духа, я, возможно, поддержал бы вас :)

// Include the Windows header file that’s needed for all Windows applications

#include <windows.h>
#include <string.h>
#include <string>
#include <tchar.h>
#include <stdlib.h>
#include <list>
#include <iostream>
HINSTANCE hInst; // global handle to hold the application instance
HWND wndHandle; // global variable to hold the window handle
// make class name into a global variable
TCHAR szClassName[ ] = _T(«WindowsApp»);

// forward declarations
bool initWindow( HINSTANCE hInstance );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
// This is winmain, the main entry point for Windows applications
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow )
{
// Initialize the window
if ( !initWindow( hInstance ) )
return false;
// main message loop:
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message!=WM_QUIT )
{
// Check the message queue
while (GetMessage(&msg, wndHandle, 0, 0) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return (int) msg.wParam;
}

// bool initWindow( HINSTANCE hInstance )
//initWindow registers the window class for the application, creates the window

bool initWindow( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
// Fill in the WNDCLASSEX structure. This describes how the window
// will look to the system
wcex.cbSize = sizeof(WNDCLASSEX); // the size of the structure
wcex.style = CS_HREDRAW | CS_VREDRAW; // the class style
wcex.lpfnWndProc = (WNDPROC)WndProc; // the window procedure callback
wcex.cbClsExtra = 0; // extra bytes to allocate for this class
wcex.cbWndExtra = 0; // extra bytes to allocate for this instance
wcex.hInstance = hInstance; // handle to the application instance
wcex.hIcon = 0; // icon to associate with the application
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);// the default cursor
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // the background color
wcex.lpszMenuName  = NULL; // the resource name for the menu
wcex.lpszClassName = _T(«WindowsApp»); // the class name being created
wcex.hIconSm = 0; // the handle to the small icon

if (!RegisterClassEx(&wcex));
return 0;
// Create the window
wndHandle = CreateWindowEx(
0,
 szClassName,
 _T(«Windows App»),
WS_OVERLAPPEDWINDOW,
// the window class to use
// the title bar text
// the window style

CW_USEDEFAULT, // the starting x coordinate
CW_USEDEFAULT, // the starting y coordinate
640, // the pixel width of the window
480, // the pixel height of the window
NULL, // the parent window; NULL for desktop
NULL, // the menu for the application; NULL for
// none
hInstance, // the handle to the application instance
NULL); // no values passed to the window
// Make sure that the window handle that is created is valid
if (!wndHandle)
return false;
// Display the window on the screen
ShowWindow(wndHandle, SW_SHOW);
UpdateWindow(wndHandle);
return true;
}

Понравилась статья? Поделить с друзьями:
  • Ошибка c2589 недопустимая лексема справа от
  • Ошибка c257 00 форд фокус 3
  • Ошибка c2440 невозможно преобразовать int в int
  • Ошибка c2440 инициализация невозможно преобразовать
  • Ошибка c240201 kia какой электромотор