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

Big*_*066 1 c++ arduino

这编译得很好(Arduino):

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

void IRAM_ATTR ProgressInit(ProgressStore aProgressStore){
}
Run Code Online (Sandbox Code Playgroud)

忽略 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) {
 

 |                   ^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

Joh*_*eau 5

请参阅此处:https ://stackoverflow.com/a/17493585/2027196

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;
}
Run Code Online (Sandbox Code Playgroud)

一种解决方案是将结构和类移动到它们自己的.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
Run Code Online (Sandbox Code Playgroud)

主程序

#include "ProgressStore.h"

void ProgressInit(ProgressStore aProgressStore) {//, uint32_t SectorNr) {
//  ProgressStore.1stSector = SectorNr;
}
Run Code Online (Sandbox Code Playgroud)

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