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

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#include <windows.h>  
#include "mditest.h"  
 
 
HWND      hWndClient = NULL;
HINSTANCE hInst;   // current instance
 
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);  
LPCTSTR lpszAppName  = L"MyMDIApp";
LPCTSTR lpszChild    = L"MDIChild";
LPCTSTR lpszTitle    = L"MDI Test Application"; 
 
 
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,LPTSTR lpCmdLine, int nCmdShow)
{
   MSG        msg;
   HWND       hWnd; 
   WNDCLASSEX wc;
 
   // Register the main application window class.
   //............................................
   wc.style         = CS_HREDRAW | CS_VREDRAW;
   wc.lpfnWndProc   = (WNDPROC)WndProc;       
   wc.cbClsExtra    = 0;                      
   wc.cbWndExtra    = 0;                      
   wc.hInstance     = hInstance;              
   wc.hIcon         = LoadIcon( hInstance, lpszAppName ); 
   wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
   wc.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE+1);
   wc.lpszMenuName  = lpszAppName;              
   wc.lpszClassName = lpszAppName;              
   wc.cbSize        = sizeof( WNDCLASSEX );
   //wc.hIconSm       = LoadImage( hInstance, lpszAppName, 
   //                              IMAGE_ICON, 16, 16,
   //                              LR_DEFAULTCOLOR );
 
   if ( !RegisterClassEx( &wc ) )
      return( FALSE );
 
   // Register the window class for the MDI child windows.
   //.....................................................
   wc.lpfnWndProc   = (WNDPROC)ChildWndProc;
   wc.hIcon         = LoadIcon( hInstance, lpszChild );
   wc.hCursor       = LoadCursor( NULL, IDC_ARROW );
   wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
   wc.lpszMenuName  = NULL;
   wc.lpszClassName = lpszChild;
   wc.cbSize        = sizeof( WNDCLASSEX );
   //wc.hIconSm       = LoadImage( hInstance, lpszChild, 
   //                              IMAGE_ICON, 16, 16,
   //                              LR_DEFAULTCOLOR );
 
   if ( !RegisterClassEx( &wc ) )
      return( FALSE );
 
   hInst = hInstance; 
 
   // Create the main application window.
   //....................................
   hWnd = CreateWindow( lpszAppName, 
                        lpszTitle,    
                        WS_OVERLAPPEDWINDOW, 
                        CW_USEDEFAULT, 0, 
                        CW_USEDEFAULT, 0,  
                        NULL,              
                        NULL,              
                        hInstance,         
                        NULL               
                      );
 
   if ( !hWnd ) 
      return( FALSE );
 
   ShowWindow( hWnd, nCmdShow ); 
   UpdateWindow( hWnd );         
 
   while( GetMessage( &msg, NULL, 0, 0) )   
   {
      if ( hWndClient && TranslateMDISysAccel( hWndClient, &msg ) )
         continue;
 
      TranslateMessage( &msg ); 
      DispatchMessage( &msg );  
   }
 
   return( msg.wParam ); 
}
 
// An ID that is different than all menu ids.
//...........................................
#define ID_CHILDWINDOW 1000 
 
LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
   switch( uMsg )
   {
      case WM_CREATE :
              {
                 CLIENTCREATESTRUCT ccs;
    
                 // Assign the 'Window' menu.
                 //..........................             
                 ccs.hWindowMenu  = GetSubMenu( GetMenu( hWnd ), 1 );
                 ccs.idFirstChild = ID_CHILDWINDOW;
 
                 // Create the client window.
                 //..........................
                 hWndClient = CreateWindowEx( WS_EX_CLIENTEDGE, 
                                              L"MDICLIENT", NULL,
                                              WS_CHILD | WS_CLIPCHILDREN, 
                                              0, 0, 0, 0,
                                              hWnd, (HMENU)0xCA0, hInst, &ccs);
 
                 ShowWindow( hWndClient, SW_SHOW );
              }
              break;
 
      case WM_SIZE :
              // Size the client window to the size of the client
              // area of the main application window.
              //.................................................
              MoveWindow( hWndClient, 0, 0, LOWORD( lParam ), 
                                            HIWORD( lParam ), TRUE );
              break;
     
      case WM_COMMAND :
              switch( LOWORD( wParam ) )
              {
                 case IDM_NEW :
                     {
                        HWND hWndChild;
 
                        // Create a new child window.
                        //...........................
                        hWndChild = CreateMDIWindow( (LPTSTR)lpszChild, 
                                         L"Document", 0L,
                                         CW_USEDEFAULT, CW_USEDEFAULT, 
                                         CW_USEDEFAULT, CW_USEDEFAULT,
                                         hWndClient, hInst, 0L);
 
                        ShowWindow( hWndChild, SW_SHOW );
                     }
                     break;
 
                 case IDM_CLOSE :
                     {
                        HWND hActiveWnd;
                        
                        // Close the active child window.
                        //...............................
                        hActiveWnd = (HWND)SendMessage( hWndClient, 
                                                        WM_MDIGETACTIVE, 0, 0 );
                        if ( hActiveWnd )
                           SendMessage( hWndClient, WM_MDIDESTROY, (WPARAM)hActiveWnd, 0 );
                     }
                     break;
 
                 case IDM_CASCADE :
                        CascadeWindows( hWndClient, MDITILE_SKIPDISABLED,
                                        NULL, 0, NULL );
                        break;
 
                 case IDM_TILEHORZ :
                        TileWindows( hWndClient, MDITILE_HORIZONTAL, 
                                     NULL, 0, NULL );
                        break;
 
                 case IDM_TILEVERT :
                        TileWindows( hWndClient, MDITILE_VERTICAL, 
                                     NULL, 0, NULL );
                        break;
 
                 case IDM_ARRANGE :
                        ArrangeIconicWindows( hWndClient );
                        break;
 
                 case IDM_ABOUT :
                        DialogBox( hInst, L"AboutBox", hWnd, (DLGPROC)About );
                        break;
 
                 case IDM_EXIT :
                        DestroyWindow( hWnd );
                        break;
 
                 default :
                        return( DefFrameProc( hWnd, hWndClient, 
                                              uMsg, wParam, lParam ) );      
              }
              break;
      
      case WM_DESTROY :
              PostQuitMessage(0);
              break;
 
      default :
            return( DefFrameProc( hWnd, hWndClient, uMsg, wParam, lParam ) );
   }
 
   return( 0L );
}
 
 
LRESULT CALLBACK ChildWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
   //switch( uMsg )
   //{
   //   default :
   //         return( DefMDIChildProc( hWnd, uMsg, wParam, lParam ) );
   //}
 
   return( 0L );
}
 
 
LRESULT CALLBACK About( HWND hDlg,           
                        UINT message,        
                        WPARAM wParam,       
                        LPARAM lParam)
{
   switch (message) 
   {
       case WM_INITDIALOG: 
               return (TRUE);
 
       case WM_COMMAND:                              
               if (   LOWORD(wParam) == IDOK         
                   || LOWORD(wParam) == IDCANCEL)    
               {
                       EndDialog(hDlg, TRUE);        
                       return (TRUE);
               }
               break;
   }
 
   return (FALSE); 
}

// 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;
}

Я обновил старый проект с VC6 до VS2008, и теперь я получаю эту ошибку компиляции:

error C2731: 'wWinMain' : function cannot be overloaded

В этих строках кода:

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

Тот же проект прекрасно компилируется под VC6.

4

Решение

Спасибо всем, я наконец нашел настоящего виновника, это опечатка, я использую LPSTR lpCmdLine вместо LPTSTR lpCmdLine, Настоящая загадка заключается в том, почему он вообще скомпилирован под VC6 — он использовал wWinMain, но каким-то образом это было нормально для lpCmdLine, чтобы быть char * вместо WCHAR *,

Теперь я изменил это на:

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

И это работает под VS2008 тоже.

Редактировать: Я успешно скомпилировал и даже запустил программу с этим определением функции под VC6:

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

Интересно, что замена float nCmdShow в double nCmdShow я даю ошибку компоновщика, я полагаю, потому что float 32-битный, а double — нет.

9

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

У меня была такая же ошибка с Консольное приложение Win32. Исправление было:

  1. открыто проект > Свойства …,
  2. расширять Свойства конфигурации > Linker > система
  3. Задавать SubSystem в Не установлен
  4. Нажмите Хорошо

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;
}

  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;
}

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Ошибки компеляции C2733 и C2731 (wWinMain)
    , VS2012 with Platform Toolset VS2008 (v90)

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    10.07.13, 09:21

      Senior Member

      ****

      Рейтинг (т): 12

      Всем привет!

      MyDLL.cpp

      ExpandedWrap disabled

        extern «C» int WINAPI wWinMain(HINSTANCE hExeInstance, IInstallerStub* pInstallerStub)  

        {

            //…

        }

      MyDLL.def

      ExpandedWrap disabled

        LIBRARY MyFirstDLL

        EXPORTS

            wWinMain     PRIVATE

      Настройки проекта:
      Target Name: MyFirstDLL
      Module Definition File: MyDLL.def

      При компиляции выдает ошибки:

      ExpandedWrap disabled

        Error C2733: second C linkage of overloaded function ‘wWinMain’ not allowed

        Error C2731: ‘wWinMain’ : function cannot be overloaded

      Этот же код компилится в VS2003 без проблем.
      Настройки проектов VS2003 и VS2012 вроде бы все совпадают.
      Подскажите, плиз, в чем может быть проблема?

      Заранее всем благодарен!


      Kray74



      Сообщ.
      #2

      ,
      10.07.13, 09:31

        Цитата -=CAP=- @ 10.07.13, 09:21

        Подскажите, плиз, в чем может быть проблема?

        В extern «C» — убери его.


        -=CAP=-



        Сообщ.
        #3

        ,
        10.07.13, 09:36

          Senior Member

          ****

          Рейтинг (т): 12

          Цитата Kray74 @ 10.07.13, 09:31

          В extern «C» — убери его.

          Ошибка

          ExpandedWrap disabled

            Error C2733: second C linkage of overloaded function ‘wWinMain’ not allowed

          ушла, но

          ExpandedWrap disabled

            Error C2731: ‘wWinMain’ : function cannot be overloaded

          всё же присутствует


          Axis



          Сообщ.
          #4

          ,
          10.07.13, 09:48

            В объявлении и реализации стоит extern «C»?


            Kray74



            Сообщ.
            #5

            ,
            10.07.13, 09:56

              Ты же DLL компилируешь, почему тогда не

              ExpandedWrap disabled

                BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID)

              ?

              Wizard

              B.V.



              Сообщ.
              #6

              ,
              10.07.13, 13:00

                -=CAP=-, зачем тебе в DLL WinMain, а тем более, зачем она тебе в экспорте?


                -=CAP=-

                  


                Сообщ.
                #7

                ,
                10.07.13, 13:32

                  Senior Member

                  ****

                  Рейтинг (т): 12

                  Kray74, DllMain так же присутствует.
                  B.V., не WinMain, а wWinMain.

                  В общем, отбой воздушной тревоги.

                  Функция wWinMain — пользовательская, потому и в экспорте.
                  А имя ей токое дали, даже не знаю почему (так сложилось исторически).
                  Переименовал и вуаля — все компилится.

                  Неопонятно остальось только одно:
                  почему в VS2003 компилится, а в VS2012(v90) — нет :wall:

                  Wizard

                  B.V.



                  Сообщ.
                  #8

                  ,
                  10.07.13, 14:01

                    Цитата -=CAP=- @ 10.07.13, 13:32

                    B.V., не WinMain, а wWinMain.

                    Это одно и то же. wWinMain отличается юникодной сигнатурой

                    Цитата -=CAP=- @ 10.07.13, 13:32

                    А имя ей токое дали, даже не знаю почему

                    Возможно, раньше проект был EXE?


                    -=CAP=-



                    Сообщ.
                    #9

                    ,
                    10.07.13, 14:04

                      Senior Member

                      ****

                      Рейтинг (т): 12

                      Цитата B.V. @ 10.07.13, 14:01

                      Это одно и то же. wWinMain отличается юникодной сигнатурой

                      таки да, описана в WTL-ных файлах

                      Цитата B.V. @ 10.07.13, 14:01

                      Возможно, раньше проект был EXE?

                      там ОЧЕНЬ лихо закручен сюжет: одни и теже файлы используются в разных проектах

                      0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                      0 пользователей:

                      • Предыдущая тема
                      • C/C++: Системное программирование и WinAPI
                      • Следующая тема

                      Рейтинг@Mail.ru

                      [ Script execution time: 0,0357 ]   [ 16 queries used ]   [ Generated: 5.06.23, 23:59 GMT ]  

                      Понравилась статья? Поделить с друзьями:
                    • Ошибка компилятора c2679
                    • Ошибка компиляции для платы arduino nano every
                    • Ошибка компилятора c2678
                    • Ошибка компиляции для платы arduino mega
                    • Ошибка компилятора c2665