I have the following code:
// note: this implicity defines onoff_pub_0 as a static
ESP_BLE_MESH_MODEL_PUB_DEFINE(onoff_pub_0, 2 + 3, ROLE_NODE);
static esp_ble_mesh_gen_onoff_srv_t onoff_server_0 = {
.rsp_ctrl.get_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP,
.rsp_ctrl.set_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP,
};
// ...
static esp_ble_mesh_model_t root_models[] = {
ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(&onoff_pub_0, &onoff_server_0),\
// ...
};
I'd like to be able to isolate these definition into separate file, and root_models
in a separate file (to allow for reusability of code), but I can't seem to get around accessing static variables from another file (and yes, I've read a lot of posts on StackOverflow about using statics in C for encapsulation)... Is there any better option when the library I'm using implements static variables in their macros?
FYI, here's a more complete example if someone wants to propose a more general architecture approach...
If onoff_pub_0
is unavoidably static
(due to to the library you're using), and you want to access that variable in a different file to where it's defined, then you can create a function to return a pointer to onoff_pub_0
(as long as you know what C type onoff_pub_0
is).
So in file1.c you have (where I'm using onoff_pub_t
for the type):
ESP_BLE_MESH_MODEL_PUB_DEFINE(onoff_pub_0, 2 + 3, ROLE_NODE);
static esp_ble_mesh_gen_onoff_srv_t onoff_server_0 = {
.rsp_ctrl.get_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP,
.rsp_ctrl.set_auto_rsp = ESP_BLE_MESH_SERVER_AUTO_RSP,
};
static esp_ble_mesh_model_t root_models[] = {
ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(&onoff_pub_0, &onoff_server_0),\
// ...
};
// Function to return a pointer to onoff_pub_0
onoff_pub_t GetOnOff0PubPtr(void)
{
return &onoff_pub_0;
}
Then in file1.h you have:
#include "some header file .h" // include whatever is necessary for onoff_pub_t
onoff_pub_t GetOnOff0PubPtr(void);
And now in file2.c:
#include "file1.h"
onoff_pub_t *on_off_pub_0_ptr = GetOnOff0PubPtr(); // get a pointer to static on_off_pub_0 in file2.c
if (*on_off_pub_0_ptr == ...) // do something with the value of on_off_pub_0 by dereferencing on_off_pub_0_ptr