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

2

1 Answer

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. } } 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy