Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaring a static variable in C++

I run into the following problem and idk if it can be solved in an elegant way:

  1. I need to statically initialize an interface wifi and sntp in main. I can't do it in global space because they are dependent on a task scheduler which is started only when main is called.
  2. The wifi API takes a callback which requires the sntp interface to be present to start it, thus capturing it by reference.
  3. The sntp service depends on the wifi service to be started as the wifi service will start up the network interface that sntp needs (I know this is bad design but I'm kind of fixed on this solution right now).

So I'm landing in cyclic dependency land once again. My initial thought to fight through this was to just forward declare the static variable but it turns out this doesn't work in the way that I thought, as declaring it "extern" conflicts with the later definition.

Here's the code:

Demo

#include <cstdio>
#include <functional>

struct wifi_config {
    std::function<void()> callback;
};

struct wifi {
    wifi(const wifi_config& cfg) {} 
};

struct sntp {
    sntp()  = default;

    auto start() -> void { printf("SNTP start!\n"); }
};

int main() {

    extern sntp mysntp;

    static wifi mywifi(wifi_config{
        .callback = [&]() -> void {
            mysntp.start();
        }
    });

    static sntp mysntp;
}

And here's the error:

<source>:28:17: error: 'sntp mysntp' conflicts with a previous declaration
   28 |     static sntp mysntp;
      |           

How do I get around this?

like image 624
glades Avatar asked Aug 25 '26 04:08

glades


1 Answers

It if it is extern you are saying that mysntp is defined in another compilation unit. By declaring it static you are declaring it and saying it is only available in this compilation unit (cpp file). Those are not compatible.

like image 147
Henrique Bucher Avatar answered Aug 27 '26 21:08

Henrique Bucher