1

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?

andig
  • 13,378
  • 13
  • 61
  • 98
  • The compile error looks like it has nothing to do with the code you posted ? What's inside webserver.cpp thats defining g_pass multiple times? – Unimportant Nov 13 '15 at 16:01
  • Updated. I'm wondering if the definition in the header is possible at all as all answers indicate moving definition to c file or inlining. Both are not applicable here. – andig Nov 13 '15 at 16:06

1 Answers1

1

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.

Community
  • 1
  • 1
Kenney
  • 9,003
  • 15
  • 21
  • That means the best practice for global variables is defining them in a .cpp file, not in .h? – andig Nov 13 '15 at 16:07