8

我正在用 Visual C++ 编写代码来访问串行端口。

代码如下: -

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

在上面的代码中,我在if in line处遇到错误

if(hserial==INVALID_HANDLE_VALUE)

错误如下:-

Error:expected a declaration

在if语句的末尾,我在两个大括号}处都收到相同的错误

我想知道为什么我会收到此错误以及如何解决它

4

1 回答 1

9

我想你可能想读这个。问题是您试图if在只有声明有效的命名空间范围(全局命名空间)中使用语句。

您需要将逻辑包装在某种函数中。

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.
  }
}
于 2013-02-27T04:22:22.757 回答