Vladislavv 1 / 1 / 2 Регистрация: 30.07.2014 Сообщений: 98 |
||||
1 |
||||
04.08.2014, 13:13. Показов 5096. Ответов 1 Метки нет (Все метки)
пишет
0 |
17409 / 9246 / 2259 Регистрация: 30.01.2014 Сообщений: 16,167 |
|
04.08.2014, 13:18 |
2 |
void move (int mv, int trn, int pl, int comp) У этой функции закрывающую скобку забыл. PS. На будущее пользуйся пожалуйста тегами форматирования кода при создании постов и тем.
1 |
Using Visual Studio 2013 C++, I got compilation errors that I couldn’t explain.
The compilation errors were:
*main.cpp(325): error C2601: ‘FLAG’ : local function definitions are illegal
main.cpp(323): this line contains a ‘{‘ which has not yet been matched
main.cpp(326): fatal error C1075: end of file found before the left brace ‘{‘ at ‘main.cpp(323)’ was matched*
But there was nothing wrong with my code. I counted all brackets and the number matched. There weren’t any function inside another function.
I solved it by removing all «//» comments from the source code. It seems that the reason for that is bad line formatting which causes the compiler to miss a line break, so the line after a comment is treated as a comment as well.
For example:
// This is a comment
This_is_a_line;
is treated as:
// This is a comment This_is_a_line;
There are many posts of the net about similar problems and some even suggested that they could be caused by a memory (RAM) fault on the machine, so before you replace your RAM, just remove the comments and see…
- Michael Haephrati מיכאל האפרתי
Vladislavv 1 / 1 / 2 Регистрация: 30.07.2014 Сообщений: 98 |
||||
1 |
||||
04.08.2014, 13:13. Показов 4828. Ответов 1 Метки нет (Все метки)
пишет
__________________ 0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
04.08.2014, 13:18 |
2 |
void move (int mv, int trn, int pl, int comp) У этой функции закрывающую скобку забыл. PS. На будущее пользуйся пожалуйста тегами форматирования кода при создании постов и тем. 1 |
Ниже приведен мой код на C ++. Я получаю эту ошибку:
C2601: ‘main’: определения локальных функций недопустимы
Почему я это понимаю?
BOOL CBasicApp::InitInstance()
{
typedef BOOL (__stdcall *pFunc) ();
int main(int argc, char* argv[])
{
pFunc pf = 0;
HMODULE hMod = 0;
hMod = LoadLibrary("dbgghelp.dll");
if (!hMod)
{
printf("File not found: Dbgghelp.DLLn");
return 0;
}
pf = GetProcAddress(hMod,"L100A6F95");
-8
Решение
main
является функцией точки входа для консольного приложения. Это должно быть в глобальном масштабе. В любом случае вы не можете вкладывать функции в другие функции.
Попробуйте что-то более похожее на это:
BOOL CBasicApp::InitInstance()
{
typedef BOOL (__stdcall *pFunc)();
HMODULE hMod = LoadLibrary("dbgghelp.dll");
if (!hMod)
{
printf("Error loading dbgghelp.DLLn");
return FALSE;
}
pFunc pf = GetProcAddress(hMod, "L100A6F95");
if (!pf)
{
printf("Error finding L100A6F95 functionn");
FreeLibrary(hMod);
return FALSE;
}
if (!pf())
{
printf("L100A6F95 function failedn");
FreeLibrary(hMod);
return FALSE;
}
FreeLibrary(hMod);
return TRUE;
}
...
int main(int argc, char* argv[])
{
CBasicApp app;
if (app.InitInstance())
{
...
}
else
{
...
}
}
0
Другие решения
Вам нужно переместить main
функционировать из InitInstance
функция тела.
В C ++ невозможно определить вложенные функции внутри других функций (кроме лямбда-функций, но они являются выражениями, а не определениями функций).
2
спасибо друзьям всем, кто комментирует и помогает .. исправлено только что добавленным в мой файл .h / header кодом
typedef BOOL (__stdcall *pFunc) ();
int main(int argc, char* argv[]);
ниже моего
public:
virtual BOOL InitInstance();`
тогда его успешная компиляция не вызывает ошибок … но теперь моя проблема заключается в том, почему мой mainapp.exe не запускается, когда я запускаю панель запуска, кстати, моя dgghelp.dll была защитой игры для использования ce, макросов и прочего, я просто переименовал его … есть некоторые, я думаю, дампы кода внутри ….
0
- Remove From My Forums
-
Question
-
Hi,I am a new student in C++ and having some trouble in the functions. I am getting the follow error for this function:
error C2601: ‘getChoice’ : local function definitions are illegal
int getChoice(int User_Choice)
{
//Get the user’s choice.
cout << «tt Please pick a number 1, 2 or 3: n»;
cin >> User_Choice;
return(User_Choice);
}And the following error for this function:
error C2601: ‘getRandom’ : local function definitions are illegal
int getRandom ()
{
//Get the random number.
int Random = 1 + rand() % 3;
return (Random);
}I also have a question regarding seeding the random number generator. I’ve included the following further up in the program but wonder if I should be including it within the function?
unsigned seed = time(0); //Get the system time and use 0 for the argument.
srand(seed); //Seed the random number generator.Can you help me?
Thank you,
ElizabethN
Answers
-
>Then I should put that inside my function.
Why?
>Then it only runs again if the user chooses to play again.
>Correct?Wrong. Read what I said again. Do you not understand
what «*once* during the program’s execution» means?If a user chooses to play again, that’s still the same
execution cycle/lifetime. It only becomes a new
execution if the program itself is started again.— Wayne
-
Edited by
Tuesday, February 21, 2012 1:26 AM
-
Marked as answer by
Rob Pan
Thursday, March 1, 2012 9:23 AM
-
Edited by
i have the following code that works well when it is win32 console application
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
if( !InitBoard() )
{
return 1;
}
HWND hDialog = 0;
hDialog = CreateDialog (hInst,
MAKEINTRESOURCE (IDD_MAIN),
0,
DialogProc);
if (!hDialog)
{
char buf [100];
wsprintf (buf, «Error x%x», GetLastError ());
MessageBox (0, buf, «CreateDialog», MB_ICONEXCLAMATION | MB_OK);
return 1;
}
#if !defined (_WRITE_MPEG_ )
InitBufferHandling();
StartRTPProcess();
// give vlc some time to get started before shoving buffers at it…
#endif
Sleep(250);
if( !StartAcquisition() )
return 1;
g_hWnd = hDialog;
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsDialogMessage(hDialog, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
BOOL CALLBACK DialogProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_CLOSE:
PostQuitMessage(0);
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
ShutDownAcquisition();
PostQuitMessage(1);
return FALSE;
case IDC_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, About);
return TRUE;
default:
break;
}
default:
return FALSE;
}
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
int SelectBoard()
{
DialogBox(hInst, MAKEINTRESOURCE(IDD_SELECT_BOARD), g_hWnd, SelectBoardProc);
return g_SelectedBoard;
}
BOOL CALLBACK SelectBoardProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_INITDIALOG:
{
int nBoards = GetBoardCount();
SelBoard BoardInfo;
char ButtonCaption[64];
int nButtonHeight = 17;
for( int i = 0; i < nBoards; i++ )
{
GetBoardSelection( i, &BoardInfo );
wsprintf( ButtonCaption, «%s %s %s», BoardInfo.szBoardName, BoardInfo.szSerialNumber,
BoardInfo.bClaimed ? «(Busy)» : » » );
CreateWindowEx( 0, TEXT(«BUTTON»), ButtonCaption, WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
7, 7 + i*nButtonHeight, 282, nButtonHeight, hDlg, (HMENU)(BOARD_RADIO_1 + i), hInst, 0 );
}
g_SelectedBoard = 0;
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
switch (LOWORD(wParam))
{
case BOARD_RADIO_1:
case BOARD_RADIO_1 + 1:
case BOARD_RADIO_1 + 2:
case BOARD_RADIO_1 + 3:
case BOARD_RADIO_1 + 4:
case BOARD_RADIO_1 + 5:
g_SelectedBoard = LOWORD(wParam) — BOARD_RADIO_1;
return TRUE;
break;
case IDOK:
EndDialog(hDlg, LOWORD(wParam));
return FALSE;
}
}
}
return FALSE;
}
i tryed to convert my program into services and i wrote the following:-
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
#define SLEEP_TIME 5000
#define LOGFILE «C:MyServicesmemstatus1.txt»
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
int InitService();
bool eventchecking;
int WriteToLog(char* str)
{
FILE* log;
log = fopen(LOGFILE, «a+»);
if (log == NULL)
return -1;
fprintf(log, «%sn», str);
fclose(log);
return 0;
}
void main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = «MemoryStatus»;
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// Start the control dispatcher thread for our service
StartServiceCtrlDispatcher(ServiceTable);
}
// Service initialization
int InitService()
{
int result;
result = WriteToLog(«Monitoring started.»);
return(result);
}
void ServiceMain(int argc, char** argv)
{
int error;
MEMORYSTATUS memory;
char buffer[16];
int result;
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler(
«MemoryStatus»,
(LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
// Registering Control Handler failed
return;
}
// Initialize Service
error = InitService();
if (error)
{
// Initialization failed
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus, &ServiceStatus);
return;
}
// We report the running status to SCM.
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
// The worker loop of a service
while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
void myfunc(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
if( !InitBoard() )
{
return 1;
}
HWND hDialog = 0;
hDialog = CreateDialog (hInst,
MAKEINTRESOURCE (IDD_MAIN),
0,
DialogProc);
if (!hDialog)
{
char buf [100];
wsprintf (buf, «Error x%x», GetLastError ());
MessageBox (0, buf, «CreateDialog», MB_ICONEXCLAMATION | MB_OK);
return 1;
}
#if !defined (_WRITE_MPEG_ )
InitBufferHandling();
StartRTPProcess();
// give vlc some time to get started before shoving buffers at it…
#endif
Sleep(250);
if( !StartAcquisition() )
return 1;
g_hWnd = hDialog;
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsDialogMessage(hDialog, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//return (int) msg.wParam;
if (eventchecking)
{
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus, &ServiceStatus);
return;
}
Sleep(SLEEP_TIME);
}
// return;
}
return;
}
BOOL CALLBACK DialogProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_CLOSE:
PostQuitMessage(0);
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
ShutDownAcquisition();
PostQuitMessage(1);
return FALSE;
case IDC_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, About);
return TRUE;
default:
break;
}
default:
return FALSE;
}
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
int SelectBoard()
{
DialogBox(hInst, MAKEINTRESOURCE(IDD_SELECT_BOARD), g_hWnd, SelectBoardProc);
return g_SelectedBoard;
}
BOOL CALLBACK SelectBoardProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_INITDIALOG:
{
int nBoards = GetBoardCount();
SelBoard BoardInfo;
char ButtonCaption[64];
int nButtonHeight = 17;
for( int i = 0; i < nBoards; i++ )
{
GetBoardSelection( i, &BoardInfo );
wsprintf( ButtonCaption, «%s %s %s», BoardInfo.szBoardName, BoardInfo.szSerialNumber,
BoardInfo.bClaimed ? «(Busy)» : » » );
CreateWindowEx( 0, TEXT(«BUTTON»), ButtonCaption, WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
7, 7 + i*nButtonHeight, 282, nButtonHeight, hDlg, (HMENU)(BOARD_RADIO_1 + i), hInst, 0 );
}
g_SelectedBoard = 0;
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
switch (LOWORD(wParam))
{
case BOARD_RADIO_1:
case BOARD_RADIO_1 + 1:
case BOARD_RADIO_1 + 2:
case BOARD_RADIO_1 + 3:
case BOARD_RADIO_1 + 4:
case BOARD_RADIO_1 + 5:
g_SelectedBoard = LOWORD(wParam) — BOARD_RADIO_1;
return TRUE;
break;
case IDOK:
EndDialog(hDlg, LOWORD(wParam));
return FALSE;
}
}
}
return FALSE;
}
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
// WriteToLog(«Monitoring stopped.»);
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
//WriteToLog(«Monitoring stopped.»);
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
// Report current status
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
when i compile this i am getting an error of ‘myfunc’ : local function definitions are illegal
What should i do to remove it?
Tarun
i have the following code that works well when it is win32 console application
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
if( !InitBoard() )
{
return 1;
}
HWND hDialog = 0;
hDialog = CreateDialog (hInst,
MAKEINTRESOURCE (IDD_MAIN),
0,
DialogProc);
if (!hDialog)
{
char buf [100];
wsprintf (buf, «Error x%x», GetLastError ());
MessageBox (0, buf, «CreateDialog», MB_ICONEXCLAMATION | MB_OK);
return 1;
}
#if !defined (_WRITE_MPEG_ )
InitBufferHandling();
StartRTPProcess();
// give vlc some time to get started before shoving buffers at it…
#endif
Sleep(250);
if( !StartAcquisition() )
return 1;
g_hWnd = hDialog;
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsDialogMessage(hDialog, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
BOOL CALLBACK DialogProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_CLOSE:
PostQuitMessage(0);
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
ShutDownAcquisition();
PostQuitMessage(1);
return FALSE;
case IDC_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, About);
return TRUE;
default:
break;
}
default:
return FALSE;
}
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
int SelectBoard()
{
DialogBox(hInst, MAKEINTRESOURCE(IDD_SELECT_BOARD), g_hWnd, SelectBoardProc);
return g_SelectedBoard;
}
BOOL CALLBACK SelectBoardProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_INITDIALOG:
{
int nBoards = GetBoardCount();
SelBoard BoardInfo;
char ButtonCaption[64];
int nButtonHeight = 17;
for( int i = 0; i < nBoards; i++ )
{
GetBoardSelection( i, &BoardInfo );
wsprintf( ButtonCaption, «%s %s %s», BoardInfo.szBoardName, BoardInfo.szSerialNumber,
BoardInfo.bClaimed ? «(Busy)» : » » );
CreateWindowEx( 0, TEXT(«BUTTON»), ButtonCaption, WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
7, 7 + i*nButtonHeight, 282, nButtonHeight, hDlg, (HMENU)(BOARD_RADIO_1 + i), hInst, 0 );
}
g_SelectedBoard = 0;
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
switch (LOWORD(wParam))
{
case BOARD_RADIO_1:
case BOARD_RADIO_1 + 1:
case BOARD_RADIO_1 + 2:
case BOARD_RADIO_1 + 3:
case BOARD_RADIO_1 + 4:
case BOARD_RADIO_1 + 5:
g_SelectedBoard = LOWORD(wParam) — BOARD_RADIO_1;
return TRUE;
break;
case IDOK:
EndDialog(hDlg, LOWORD(wParam));
return FALSE;
}
}
}
return FALSE;
}
i tryed to convert my program into services and i wrote the following:-
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
#define SLEEP_TIME 5000
#define LOGFILE «C:MyServicesmemstatus1.txt»
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
int InitService();
bool eventchecking;
int WriteToLog(char* str)
{
FILE* log;
log = fopen(LOGFILE, «a+»);
if (log == NULL)
return -1;
fprintf(log, «%sn», str);
fclose(log);
return 0;
}
void main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = «MemoryStatus»;
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// Start the control dispatcher thread for our service
StartServiceCtrlDispatcher(ServiceTable);
}
// Service initialization
int InitService()
{
int result;
result = WriteToLog(«Monitoring started.»);
return(result);
}
void ServiceMain(int argc, char** argv)
{
int error;
MEMORYSTATUS memory;
char buffer[16];
int result;
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler(
«MemoryStatus»,
(LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
// Registering Control Handler failed
return;
}
// Initialize Service
error = InitService();
if (error)
{
// Initialization failed
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus, &ServiceStatus);
return;
}
// We report the running status to SCM.
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
// The worker loop of a service
while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
{
void myfunc(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
if( !InitBoard() )
{
return 1;
}
HWND hDialog = 0;
hDialog = CreateDialog (hInst,
MAKEINTRESOURCE (IDD_MAIN),
0,
DialogProc);
if (!hDialog)
{
char buf [100];
wsprintf (buf, «Error x%x», GetLastError ());
MessageBox (0, buf, «CreateDialog», MB_ICONEXCLAMATION | MB_OK);
return 1;
}
#if !defined (_WRITE_MPEG_ )
InitBufferHandling();
StartRTPProcess();
// give vlc some time to get started before shoving buffers at it…
#endif
Sleep(250);
if( !StartAcquisition() )
return 1;
g_hWnd = hDialog;
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsDialogMessage(hDialog, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//return (int) msg.wParam;
if (eventchecking)
{
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -1;
SetServiceStatus(hStatus, &ServiceStatus);
return;
}
Sleep(SLEEP_TIME);
}
// return;
}
return;
}
BOOL CALLBACK DialogProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_CLOSE:
PostQuitMessage(0);
return FALSE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
ShutDownAcquisition();
PostQuitMessage(1);
return FALSE;
case IDC_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, About);
return TRUE;
default:
break;
}
default:
return FALSE;
}
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
int SelectBoard()
{
DialogBox(hInst, MAKEINTRESOURCE(IDD_SELECT_BOARD), g_hWnd, SelectBoardProc);
return g_SelectedBoard;
}
BOOL CALLBACK SelectBoardProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
switch (uMessage)
{
case WM_INITDIALOG:
{
int nBoards = GetBoardCount();
SelBoard BoardInfo;
char ButtonCaption[64];
int nButtonHeight = 17;
for( int i = 0; i < nBoards; i++ )
{
GetBoardSelection( i, &BoardInfo );
wsprintf( ButtonCaption, «%s %s %s», BoardInfo.szBoardName, BoardInfo.szSerialNumber,
BoardInfo.bClaimed ? «(Busy)» : » » );
CreateWindowEx( 0, TEXT(«BUTTON»), ButtonCaption, WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
7, 7 + i*nButtonHeight, 282, nButtonHeight, hDlg, (HMENU)(BOARD_RADIO_1 + i), hInst, 0 );
}
g_SelectedBoard = 0;
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
switch (LOWORD(wParam))
{
case BOARD_RADIO_1:
case BOARD_RADIO_1 + 1:
case BOARD_RADIO_1 + 2:
case BOARD_RADIO_1 + 3:
case BOARD_RADIO_1 + 4:
case BOARD_RADIO_1 + 5:
g_SelectedBoard = LOWORD(wParam) — BOARD_RADIO_1;
return TRUE;
break;
case IDOK:
EndDialog(hDlg, LOWORD(wParam));
return FALSE;
}
}
}
return FALSE;
}
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
// WriteToLog(«Monitoring stopped.»);
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
//WriteToLog(«Monitoring stopped.»);
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
// Report current status
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
when i compile this i am getting an error of ‘myfunc’ : local function definitions are illegal
What should i do to remove it?
Tarun
Я пишу небольшую программу на C ++. Когда я пытаюсь скомпилировать его с помощью MS VS 2013 Compiler, я получаю сообщение об ошибке: «C2601:« main »: определения локальных функций недопустимы». Что это значит? Мой код:
#include <iostream>
int n;
int pomocniczaLiczba;
using namespace std;
int ciong(int n){
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
int main()
{
cin >> n;
cout >> ciong(n);
return 0;
}
}
-1
Решение
Ваш брекетинг сломан. В результате вы пытаетесь определить свой main
функция внутри ciong
, А C ++ не поддерживает определения вложенных функций. Отсюда ошибка компилятора.
Код должен быть:
#include "stdafx.h"#include <iostream>
using namespace std;int ciong(int n)
{
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
int pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
} // <----- Oops, this was missing in your code
int main()
{
int n;
cin >> n;
cout << ciong(n) << endl;
return 0;
}
И есть другие ошибки. Например, вы имели в виду cout << ciong(n)
,
12
Другие решения
Используя Visual Studio 2013 C ++, я получил ошибки компиляции, которые я не смог объяснить.
Ошибки компиляции были:
* main.cpp (325): ошибка C2601: «FLAG»: определения локальных функций недопустимы
main.cpp (323): эта строка содержит ‘{‘, который еще не был найден
main.cpp (326): фатальная ошибка C1075: обнаружен конец файла до сопоставления левой скобки ‘{‘ at ‘main.cpp (323)’ *
Но с моим кодом не было ничего плохого. Я посчитал все скобки и число совпало. Там не было никакой функции внутри другой функции.
Я решил это, удалив все комментарии «//» из исходного кода. Кажется, что причиной этого является плохое форматирование строки, из-за которого компилятор пропускает разрыв строки, поэтому строка после комментария также рассматривается как комментарий.
Например:
// This is a comment
This_is_a_line;
рассматривается как:
// This is a comment This_is_a_line;
Есть много сообщений в сети о подобных проблемах, и некоторые даже предположили, что они могут быть вызваны ошибкой памяти (RAM) на машине, поэтому, прежде чем заменять свою RAM, просто удалите комментарии и посмотрите …
- Майкл Хефрати מיכאל האפרתי
0
Using Visual Studio 2013 C++, I got compilation errors that I couldn’t explain.
The compilation errors were:
*main.cpp(325): error C2601: ‘FLAG’ : local function definitions are illegal
main.cpp(323): this line contains a ‘{‘ which has not yet been matched
main.cpp(326): fatal error C1075: end of file found before the left brace ‘{‘ at ‘main.cpp(323)’ was matched*
But there was nothing wrong with my code. I counted all brackets and the number matched. There weren’t any function inside another function.
I solved it by removing all «//» comments from the source code. It seems that the reason for that is bad line formatting which causes the compiler to miss a line break, so the line after a comment is treated as a comment as well.
For example:
// This is a comment
This_is_a_line;
is treated as:
// This is a comment This_is_a_line;
There are many posts of the net about similar problems and some even suggested that they could be caused by a memory (RAM) fault on the machine, so before you replace your RAM, just remove the comments and see…
- Michael Haephrati מיכאל האפרתי
I’m new to C++ and learning about Inheritance and Polymorphism. We require to write an employee project that have 4 types of employee (BasePlusCommission, CommisisonEmployee, Salaried and TipWorker). My project has one main() class that I used switch method for each type of employee. I got stuck on TipWorker where we have to do Polymorphism. Here what I got so far.
int main()
{
void virtualViaPointer(const Employee * const);
{
cout << "Enter First Name: " << endl;
cin >> firstName;
cout << "Enter Last Name: " << endl;
cin >> lastName;
cout << "Enter SSN: " << endl;
cin >> SSN;
if (SSN.length() == 9)
{
SSN = true;
}
else
{
cout << "Please enter SSN again with 9 digits only:" << endl;
cin >> SSN;
}
cout << "Enter wages: " << endl;
cin >> wage;
cout << "Enter hours: " << endl;
cin >> hours;
cout << "Enter tips: " << endl;
cin >> tips;
TipWorker employee4(firstName, lastName, SSN, wage, hours, tips);
employee4.print();
cout << fixed << setprecision(2);
vector < Employee * > employees(1);
employees[0] = &employee4;
cout << "Employee processed polymorphically via dynamic binding: nn";
cout << "Virtual function calls made off base-class pointers:nn";
for (const Employee *employeePtr : employees)
virtualViaPointer(employeePtr);
void virtualViaPointer(const Employee * const baseClassPtr)
{
baseClassPtr->print();
cout << "nEarned $" << baseClassPtr->earnings() << "nn";
}
break;
}
}
When I run the project, I came up with this error:
error C2601: «virtualViaPointer»: local function definitions are
illegal
void virtualViaPointer(const Employee * const baseClassPtr)
{
baseClassPtr->print();
cout << "nEarned $" << baseClassPtr->earnings() << "nn";
}
Can anyone please help me? Thank you so much!