andig
andig

Reputation: 13868

Arduino library: multiple definitions of a global var

I know this has been asked multiple times but could not find a post relating to this specific problem:

# config.h
String g_ssid = "";

# webserver.cpp
#include "config.h"

bool saveConfig(String *ssid, String *pass)
{
  // Open config file for writing.
  File configFile = SPIFFS.open("/cl_conf.txt", "w");
  if (!configFile)
  {
    Serial.println("Failed to open cl_conf.txt for writing");
    return false;
  }

  // Save SSID and PSK.
  configFile.println(*ssid);
  configFile.println(*pass);
  configFile.close();  // <-- error in this line???

  return true;
} // saveConfig

Compile error:

webserver.cpp.o: In function `saveConfig(String*, String*)':
C:\Users\AppData\Local\Temp\build9148105163386366718.tmp/webserver.cpp:114: multiple definition of `g_pass'

Declaring as inline is not possible as the compiler complains:

'g_ssid' declared as an 'inline' variable

Obviously externing the variable from config.h doesn't make much sense as far as the purpose of config.h is concerned. How can this be solved?

Upvotes: 1

Views: 595

Answers (1)

Kenney
Kenney

Reputation: 9093

You would declare the variable in the header file:

String g_ssid;

and define it in a cpp file:

String g_ssid = "";

That way, the header can be included multiple times without re-defining the variable.

See this SO question for more details about the difference between declaring and defining.

Upvotes: 1

Related Questions