oli_taz
oli_taz

Reputation: 199

C++ 'multiple definition' compile error with static enum class members

This is an Arduino project compiled in Visual Studio (using visual micro plugin). I am getting the following error:

AutonomyHandler.cpp.o (symbol from plugin): In function AutonomyHandler::setup() const (.text+0x0): multiple definition of Module::AvailableCommandKeys ArduinoProject.cpp.o (symbol from plugin)*: (.text+0x0): first defined here

I am using an enum of CmdKeys within the class definition, and I can use the line of code below to get the available set of keys, but when I try to use it, I get multiple compile errors as seen above for each place I have used it.

Module::AvailableCommandKeys

My Module.h looks as follows:

#ifndef _MODULE_h
#define _MODULE_h

class Module {
public:
    enum CmdKeys { Forward, Left, Back, Right, Stop };
    static const CmdKeys AvailableCommandKeys[2];

    // other definitions...
};
const Module::CmdKeys Module::AvailableCommandKeys[] = { Forward, Back };

#endif

Does anyone know what is happening? I have had this issue before and making the members non-static fixed the issue but I want to keep these enum arrays static.

Upvotes: 0

Views: 1902

Answers (2)

SoronelHaetir
SoronelHaetir

Reputation: 15164

Place the line: const Module::CmdKeys Module::AvailableCommandKeys[] = { Forward, Back };

in a .cpp file.

Upvotes: 0

oli_taz
oli_taz

Reputation: 199

Since writing this post I found the answer so I thought I would post to help others anyway.

To fix the issue, you just need to move the initialisation of the static members from the definition file (.h) to the declaration file (.cpp)

Module.h looks as follows:

#ifndef _MODULE_h
#define _MODULE_h

class Module {
public:
    enum CmdKeys { Forward, Left, Back, Right, Stop };
    static const CmdKeys AvailableCommandKeys[2];

    // other definitions...
}
const Module::CmdKeys Module::AvailableCommandKeys[] = { Forward, Back };

#endif

Module.cpp looks as follows:

#include "Module.h"

const Module::CmdKeys Module::AvailableCommandKeys[] = { Forward, Back };

// Other code...

Upvotes: 1

Related Questions