C++ 结构和函数声明。为什么不编译?

C++ struct and function declaration. Why doesn't it compile?

这个编译很好(Arduino):

struct ProgressStore {
  unsigned long ProgressStart; 
  unsigned long LastStored;    
  uint32_t FirstSectorNr;      
};

void IRAM_ATTR ProgressInit(ProgressStore aProgressStore){
}

省略 IRAM_ATTR 它不再编译(?):

Verbruiksmeter:116:6: error: variable or field 'ProgressInit' declared void
  116 | void ProgressInit(ProgressStore aProgressStore){//, uint32_t SectorNr) {
      |      ^~~~~~~~~~~~
Verbruiksmeter:116:19: error: 'ProgressStore' was not declared in this scope
  116 | void ProgressInit(ProgressStore aProgressStore){//, uint32_t SectorNr) {
 

 |                   ^~~~~~~~~~~~~

看这里:

Arduino 的意思是它在 main 中找到您所有的函数定义,并在其余代码之上为每个函数生成一个函数声明。结果是您在声明 ProgressStore 结构之前尝试使用 ProgressStore。我相信 IRAM_ATTR 必须抑制这种行为。

它最终在编译之前生成了这个:

void ProgressInit(ProgressStore aProgressStore); // <-- ProgressStore not yet declared

struct ProgressStore {
  unsigned long ProgressStart; //Value of the counter at the start of the sector
  unsigned long LastStored;    //Should be new CounterValue-1, but you never know...
  uint32_t FirstSectorNr;      //1st of 2 sectors used for storage of progress
};

void ProgressInit(ProgressStore aProgressStore) {//, uint32_t SectorNr) {
//  ProgressStore.1stSector = SectorNr;
}

一个解决方案是将您的结构和 类 移动到它们自己的 .h 文件中,并将它们包含在顶部。

ProgressStore.h

#ifndef PROGRESS_STORE_H
#define PROGRESS_STORE_H

struct ProgressStore {
  unsigned long ProgressStart; //Value of the counter at the start of the sector
  unsigned long LastStored;    //Should be new CounterValue-1, but you never know...
  uint32_t FirstSectorNr;      //1st of 2 sectors used for storage of progress
};

#endif // PROGRESS_STORE_H

main.cpp

#include "ProgressStore.h"

void ProgressInit(ProgressStore aProgressStore) {//, uint32_t SectorNr) {
//  ProgressStore.1stSector = SectorNr;
}

函数声明仍然是自动生成的,但插入在您的 #includes

之后