Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : Expected a declaration

Tags:

visual-c++

I am writing a code in Visual C++ to access serial port.

Code is given below:-

#include<stdio.h>
#include<cstring>
#include<string.h>
#include<conio.h>
#include<iostream>
using namespace std;
//#include "stdafx.h"
#ifndef __CAPSTONE_CROSS_SERIAL_PORT__
#define __CAPSTONE_CROSS_SERIAL_PORT__
HANDLE hSerial= CreateFile(L"COM1", GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

if(hSerial==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND){
 //serial port does not exist. Inform user.
 }
 //some other error occurred. Inform user.
 }

In the above code I am getting error at if in line

if(hserial==INVALID_HANDLE_VALUE)

Error is given below:-

Error:expected a declaration

I am getting same error at both braces } at the end of if statement

I want to know why I am getting this error and how to resolve it

like image 775
Saad Rafey Avatar asked Feb 27 '13 04:02

Saad Rafey


1 Answers

I think you may want to read this. The problem is you are trying to use an if statement at namespace scope (global namespace) where only a declaration is valid.

You will need to wrap your logic in a function of some kind.

void mySuperCoolFunction()
{
  if(hSerial==INVALID_HANDLE_VALUE)
  {
    if(GetLastError()==ERROR_FILE_NOT_FOUND)
    {
       //serial port does not exist. Inform user.
    }
    //some other error occurred. Inform user.
  }
}
like image 175
Matthew Sanders Avatar answered Sep 22 '22 09:09

Matthew Sanders