0

Basically I want to share an enum between different classes. Separating the enum in its own header file with an unnamed namespace works fine, as long as one of the classes doesn't use the enum as a return type for a function.

The following example will not compile, it will result in a compiler error:

Test.obj : error LNK2019: unresolved external symbol "public: enum `anonymous namespace'::SharedEnum __thiscall ExampleClass::getEnum(void)" (?getEnum@ExampleClass@@QAE?AW4SharedEnum@?A0xe6c5ebe7@@XZ) referenced in function _main

As soon as you don't return the SharedEnum type from ExampleClass, but just an integer for example, everything compiles fine. I'd love to understand why this happens and what the best approach would be to share enums or variables between classes, without running into linker errors.

Any help is greatly appreciated!

Test.cpp

#include "stdafx.h"
#include "SharedEnum.h"
#include "ExampleClass.h"

SharedEnum mainEnum;

int main()
{
    mainEnum = VALUE_1;

    ExampleClass* exampleClass = new ExampleClass();
    SharedEnum exampleEnum = exampleClass->getEnum();

    return 0;
}

SharedEnum.h

#pragma once

namespace {

    enum SharedEnum {
        VALUE_1,
        VALUE_2,
        VALUE_3
    };
}

ExampleClass.h

#pragma once

#include "SharedEnum.h"

class ExampleClass
{
public:
    ExampleClass();
    ~ExampleClass();

    SharedEnum getEnum();

private:
    SharedEnum myEnum;
};

ExampleClass.cpp

#include "stdafx.h"
#include "ExampleClass.h"

ExampleClass::ExampleClass()
{
    myEnum = VALUE_2;
}

ExampleClass::~ExampleClass()
{
}

SharedEnum ExampleClass::getEnum()
{
    return myEnum;
}
navFooh
  • 183
  • 1
  • 7
  • Your issue is that the `enum` is in the anonymous namespace, it's not possible to use that in another translation unit. You must put it in a named namespace for that. – nick Mar 22 '20 at 15:04
  • Thanks @nick! That works fine indeed :) – navFooh Mar 22 '20 at 15:23
  • @nick I think you could post an answer expanding on your comment – drescherjm Mar 22 '20 at 15:37
  • 1
    @drescherjm this is definitely a duplicate, I figured somebody would flag it by now. E.g.: https://stackoverflow.com/a/37466922/9176689 I only know the answer because I read it on SO a few years ago :) – nick Mar 22 '20 at 16:19
  • @nick thanks for sharing the link to the other answer. I didn't find my question already on SO, but probably because I didn't know it was related to the nameless namespace. I found that it also works when removing the namespace altogether and declaring the enum as `static`. But I'm not sure if that's good practise. – navFooh Mar 22 '20 at 16:33
  • I found that `static` is redundant too for the enum. So it can basically just be globally declared and defined in `SharedEnum.h` – navFooh Mar 22 '20 at 16:40
  • 1
    @navFooh `static` has absolutely no meaning to an `enum`, they are `static` by definition. – nick Mar 22 '20 at 16:45

0 Answers0