Visual c++ 错误:需要一个声明 我在VisualC++中编写了一个代码来访问串口。

Visual c++ 错误:需要一个声明 我在VisualC++中编写了一个代码来访问串口。,visual-c++,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__

代码如下:-

#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.
 }
Error:expected a declaration
错误如下所示:-

#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.
 }
Error:expected a declaration
我在if语句末尾的两个大括号中得到了相同的错误


我想知道为什么会出现此错误,以及如何解决此错误。我想您可能需要阅读。问题是您试图在命名空间范围(全局命名空间)中使用
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.
  }
}

你在随机的地方写代码。这不应该在方法、类或其他东西中吗?除此之外,您还需要
#include
。而且您拥有的大多数支持代码都是不必要的或完全错误的。你不能指望弗兰肯斯坦能正常工作,而不是C++。你需要一些基本的理解。