如何在命名空间中声明外部全局,然后定义它?

How do you declare an extern global in a namespace and then define it?

本文关键字:然后 定义 全局 外部 命名空间 声明      更新时间:2023-10-16

似乎每个Arduino库都使用Arduino Serial库来打印调试消息。我目前正在尝试将此库集成到我的项目 https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/I2Cdev 中。我正在使用自己的python程序从我的atmega 2560接收消息。我想在不更改源代码的情况下尝试一些库,但由于串行库,我必须将它们的 Serial.print(( 调用转换为我自己的 API 调用。由于我必须为我弄乱的每个库执行此操作,因此我决定为串行库创建一个包装器,其中我有一个名为 Serial 的全局变量。然后,该串行变量将是定义为外部的串行包装器。

我在serial命名空间中有SerialWrapper。我希望全局变量Serial定义为 extern,也在serial命名空间中。

// SerialWrapper.h
namespace serial {
enum SerialType {
HEX,
DEC
};
class SerialWrapper {
public:
SerialWrapper(ground::Ground& ground);
void print(const char *string);
void print(uint8_t data, SerialType type);
private:
ground::Ground& ground_;
};
extern SerialWrapper Serial;
}

然后在源文件中,我像这样定义方法和全局变量

// SerialWrapper.cpp
#include "SerialWrapper.h"
serial::SerialWrapper Serial = serial::SerialWrapper(ground::Ground::reference());
serial::SerialWrapper::SerialWrapper(ground::Ground& ground) : ground_( ground )
{
}
void serial::SerialWrapper::print(const char *string)
{
ground_.sendString(string);
}
void serial::SerialWrapper::print(uint8_t data, serial::SerialType type)
{
}

尝试测试库,我在主方法中调用它

// main.cpp
using namespace serial;
int main( void )
{
Serial.print("Hello World!");
}

为了使库与我的SerialWrapper兼容,我需要它以这种方式工作。但是,当我编译时,我从main得到错误.cpp有一个undefined reference to 'serial::Serial'

您可以在 mpu 分支(即将合并到 master(下看到我所有的源代码 https://github.com/jkleve/quaddrone

为了让未定义的引用消失,我不得不像这样将声明移到命名空间之外

// SerialWrapper.h
namespace serial {
enum SerialType {
HEX,
DEC
};
class SerialWrapper {
public:
SerialWrapper(ground::Ground& ground);
void print(const char *string);
void print(uint8_t data, SerialType type);
private:
ground::Ground& ground_;
};
}
extern serial::SerialWrapper Serial;

我不知道为什么要这样做。也许其他人可以评论在命名空间中声明 extern 的问题。

我也发现了这个参考 https://www.ics.com/designpatterns/book/namespace-example.html

按照参考中的方法,您还可以按如下方式设置声明和定义

// SerialWrapper.h
namespace serial {
enum SerialType {
HEX,
DEC
};
class SerialWrapper {
public:
SerialWrapper(ground::Ground& ground);
void print(const char *string);
void print(uint8_t data, SerialType type);
private:
ground::Ground& ground_;
};
extern SerialWrapper Serial;
}

定义必须改为此。

// SerialWrapper.cpp
#include "SerialWrapper.h"
serial::SerialWrapper serial::Serial = serial::SerialWrapper(ground::Ground::reference());
相关文章: