khoih-prog / AsyncMQTT_Generic

Arduino Arduino Library for ESP8266, ESP32, Portenta_H7, STM32 and RP2040W asynchronous MQTT client implementation. This library, ported to support ESP32, WT32_ETH01 (ESP32 + LAN8720), ESP8266, Portenta_H7 (Ethernet or WiFi) and STM32 (LAN8742A or LAN8720 Ethernet), Teensy 4.1 using QNEthernet, RASPBERRY_PI_PICO_W with CYW43439 WiFi. Currently supporting TLS/SSL for ESP32 only
MIT License
64 stars 10 forks source link

Why include implementation in header? #16

Closed sinkers0s closed 2 years ago

sinkers0s commented 2 years ago

Describe the bug

The reason for we can only include AsyncMqtt_Generic.h in one .cpp or .ino is because it contains not only headers but also implementations. In particular, AsyncMqtt_Generic.h:

#include "AsyncMqttClient_Generic.hpp"
#include "AsyncMqttClient_Generic_Impl.h"

Which AsyncMqttClient_Generic_Impl.h is actually implementation instead of header. In common practice, the AsyncMqttClient_Generic_Impl.h should end with .cpp/.c instead of .h. And use compiler configuration/compile script to let compiler compile it as object(and later linking) explicitly. I'm curious why you take this approach to put header and implementation together. Is that something I missed?

And here's a problem: this approach makes abstracting/inheriting or even simply include in multiple files within same project impossible without modifying your code. For example: 1) include AsyncMqtt_Generic.h in two cpp(ino is actually cpp) of same project will result double definition. 2) include only AsyncMqttClient_Generic.hpp will result implementation not found, even if I use some trick to let compiler compile the AsyncMqttClient_Generic_Impl.h. I can do this in AsyncMqttClient_Generic_Impl.h for latter to make things work:

#include "AsyncMqttClient_Generic.hpp"

But then I have to modify your code. It's not "generic" anymore. So may I ask why would you take this approach?

khoih-prog commented 2 years ago

Have a look at HOWTO Fix Multiple Definitions Linker Error or do some more research how to use h-only libraries, with the pros and cons.

Search for the reasons in many discussions / issues in many other libraries, and how other people can currently use them.