[英]Arduino/C++: Access specific header file of structs from library
(不確定這是否僅是C / C ++問題)
我目前正在將一個大型Arduino項目的元素分割成可重用的庫-到目前為止還不錯。
但是,庫中的許多方法都返回特殊的結構,這些結構在每個庫中包含的data-types.h
文件中聲明。 我現在遇到的問題是我無法在主草圖中導入/使用這些結構。 我試過在主庫頭文件中聲明DataTypes
類的變量並通過它訪問結構,但出現error: invalid use of 'struct DataTypes::_theStructNameHere_t'
我該如何從主草圖中的庫訪問這些結構以聲明為變量類型? 我不想將包含結構體的頭文件從庫中復制到我的草圖中,也不想僅為該結構體的單個頭文件創建單獨的庫!
這是我的意思的簡單示例:
#include <Arduino.h>
#include <MyLibrary.h>
MyLibrary myLib;
void setup() {
(This is declared in the library) myLib.dataTypes._theStructNameHere_t response = myLib.getASpecialValueWhichIsOfType_theStructNameHere_t()// Gives "error: invalid use of 'struct DataTypes::_theStructNameHere_t'""
// Example usage of the struct:
Serial.print("\n Loop Card Status: ");Serial.print(response.loop_status, HEX);
if (response.number_allocated > 0) {
Serial.print("\n Devices Allocated: ");Serial.print(response.number_allocated, HEX);
} else {
if (response.loop_status != 0x123) {
// Some condition
} else {
// Something else
}
}
}
void loop() {
...
}
src/
- /data-types/
- - data-types.h
- MyLibrary.cpp
- MyLibrary.h
MyLibrary.h
: #ifndef _MYLIBRARY_H_
#define _MYLIBRARY_H_
#include <Arduino.h>
#include "./helpers/helpers.h"
...
#include "./data-types/data-types.h"
class MyLibrary {
public:
Uart *_commPort;
Helpers helpers;
...
DataTypes dataTypes;
DataTypes::_theStructNameHere_t getASpecialValueWhichIsOfType_theStructNameHere_t();
...
protected:
private:
};
#endif // _MYLIBRARY_H_
data-types.h
: #ifndef _RESPONSE_TYPES_H
#define _RESPONSE_TYPES_H
class DataTypes
{
public:
struct _theStructNameHere_t
{
bool successful;
uint8_t loop_status;
uint8_t number_allocated;
uint8_t highest_address;
uint8_t number_inputs;
uint8_t number_outputs;
}
..even more..
private:
}
#endif // _RESPONSE_TYPES_H
我可以從您的示例中獲得MCVE :
class DataTypes
{
public:
struct _theStructNameHere_t
{
};
};
class Library
{
public:
DataTypes dataTypes;
DataTypes::_theStructNameHere_t getMyDataType();
};
int main(int argc, char *argv[])
{
Library myLib;
myLib.dataTypes._theStructNameHere_t response;
}
給出與您的代碼類似的錯誤:
~$ g++ test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:20:21: error: invalid use of 'struct DataTypes::_theStructNameHere_t'
myLib.dataTypes._theStructNameHere_t response;
問題是您使用實例來訪問struct
類型/名稱。 要修復它,請更換
myLib.dataTypes._theStructNameHere_t response = ...;
與
DataTypes::_theStructNameHere_t response = ...;
筆記:
C++
的功能。 namespace Library {
namespace DataTypes {
struct _theStructNameHere_t
{
...
};
...
} /*** namespace Library::DataTypes ***/
} /*** namespace Library ***/
請閱讀有關如何提出一個好問題的 StackOverflow指南,尤其是有關“ 最小,完整和可驗證示例”的部分 。
遲早有人會告訴您,沒有C/C++
類的東西。 C
是C
, C++
是C++
; 即使基於C++
, Arduino
生活在自己的世界中。 因此,您可能想從問題中刪除C
和C++
標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.