0

Consider following code snippet,

    // header file
    #define TEXT_ENUM                //////////// HERE
    #ifdef TEXT_ENUM
        #define TEXT_HANDLING_MACRO  \
             static const char * TEXT[]; \
             static const char * getText( int _enum ) { \
                 return TEXT[_enum]; \
             }
    #else
        #define TEXT_HANDLING_MACRO
    #endif

    struct Foo {
        TEXT_HANDLING_MACRO
    };

   // cpp file
   #include "foo.h"
   #ifdef TEXT_ENUM
       const char * Foo::TEXT[] = { 
           "ONE",
           "TWO",
           "THREE",
           0
       };
   #endif

   // other_file.cpp
   #include <iostream>
   #include "foo.h"
   void bar() {
       std::cout << Foo::TEXT[0] <<std::endl;
   }

It works perfectly fine, but in following code it doesn't,

    // header file
    #ifdef TEXT_ENUM
        #define TEXT_HANDLING_MACRO  \
             static const char * TEXT[]; \
             static const char * getText( int _enum ) { \
                 return TEXT[_enum]; \
             }
    #else
        #define TEXT_HANDLING_MACRO
    #endif

    struct Foo {
        TEXT_HANDLING_MACRO
    };

   // cpp file
   #include "foo.h"
   #ifdef TEXT_ENUM
       const char * Foo::TEXT[] = { 
           "ONE",
           "TWO",
           "THREE",
           0
       };
   #endif

   // other_file.cpp
   #include <iostream>
   #define TEXT_ENUM                //////////// HERE
   #include "foo.h"
   void bar() {
       std::cout << Foo::TEXT[0] <<std::endl;
   }

The difference is the position of #include TEXT_ENUM, I get the error of undefined reference to Foo::TEXT. I have defined TEXT_ENUM before including the file.

How can I resolve it?

Oli
  • 1,313
  • 14
  • 31

0 Answers0