[英]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.