Error c2601 main недопустимые локальные определения функций

I'm writing a small program in C++. When I try to compile it using MS VS 2013 Compiler I get an error: "C2601: 'main' : local function definitions are illegall". What does it mean? My code is: #in...

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

Метки нет (Все метки)


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
#include <iostream>
#include <ctime>
using namespace std;
 
int dieroll (){
int chance=0;
srand (time(NULL));
chance=rand()%1000;
chance%=7;
return chance;
}
 
int summ (int s){
s+=s;
return s;
}
 
void winner (int pl, int comp){
if (pl>comp)
    cout <<"pl win the gamen";
else
    (comp>pl)? cout<<"comp win the gamen":cout <<"drawn";
}
 
bool ftt (){
bool fm=0;
srand (time(NULL));
fm=(rand()%1000)%2;
return fm;
}
 
void inscfft (){
    bool insc=ftt();
    if (insc==0)
        cout <<"comp throw firstn";
    else 
        cout <<"pl throw firstn";
}
 
void move (int mv, int trn, int pl, int comp){
    if (mv==0){
    cout <<"comp"<<trn<<"trow "<<comp<<endl;
    cout <<"pl"<<trn<<"trow "<<pl<<endl;
    }
    else{
    cout <<"pl"<<trn<<"trow "<<pl<<endl;
    cout <<"comp"<<trn<<"trow "<<comp<<endl;
    }
        
void main(){
    inscfft ();
    const int n=5;
int pl[n], comp[n], plsc=0, compsc=0;
for (int i=0; i<n;i++){
    pl[n]=dieroll ();
    plsc+=summ (pl[n]);
}
for (int i=0; i<n;i++){
    comp[n]=dieroll ();
    compsc+=summ (comp[n]);
}
bool chance=ftt;
for (int i=0; i<n; i++)
move (chance, i, pl[i], comp[i]);
winner (plsc, compsc);
}

пишет
6 IntelliSense: expected a ‘;’
4 error C2601: main: недопустимые локальные определения функций
5 error C1075: конец файла обнаружен ранее, чем левая фигурная скобка «{» в «c:usersвладdocumentsvisual studio 2010projectsles 8les 8dice.cpp(40)»
не пойм, где эти ошибки

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



0



16495 / 8988 / 2205

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

Сообщений: 15,611

04.08.2014, 13:18

2

Цитата
Сообщение от Vladislavv
Посмотреть сообщение

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

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:\MyServices\memstatus1.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:\MyServices\memstatus1.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

Понравилась статья? Поделить с друзьями:
  • Error c2471 cannot update program database
  • Error c2466 невозможно выделить память для массива постоянного нулевого размера
  • Error c2447 отсутствует заголовок функции возможно используется формальный список старого типа
  • Error c2447 missing function header old style formal list
  • Error c2443 конфликт размеров операндов