10

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

Saad Rafey
  • 531
  • 2
  • 6
  • 18
  • You're writing code in random places. Shouldn't that be in a method or class or something? – Dave Newton Feb 27 '13 at 04:12
  • In addition to that, you'll require `#include `. And most of the support code you do have is unneeded or outright wrong. You can't expect a Frankenstein to work properly, not in C++. You need some basic understanding. – Ben Voigt Feb 27 '13 at 06:01

1 Answers1

10

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.
  }
}
Community
  • 1
  • 1
Matthew Sanders
  • 4,875
  • 26
  • 45