0

I am trying to create an error enum and associated text descriptors aligned in the same file. I have a system.cpp file that contains the following:

#define SYSTEMCODE
#include "myerrors.h"

The file myerrors.h contains:

typedef enum errors {
    OK,
    BADERROR,
    LASTENUM  } ERR;
#ifndef SYSTEMCODE
extern char const *_errtext[];
#else
const char * _errtext[ERR::LASTENUM +1] = {
    "OK",
    "BADERROR",
    "LASTENUM"   };
#undef SYSTEMCODE
#endif

I include system.h in all sources that need error services and they do not define SYSTEMCODE.

I expect that only the system.cpp file will compile the text array and all others will simply have an extern reference. The system.cpp object does not have the _errtext array thus causing a link error. I disable pre-compiled headers and I have tried many variations of this. MSDEV does not get it right.

Any ideas?

  • this isn't c, this is C++ because of enum scoping – Jean-François Fabre Dec 01 '18 at 18:06
  • Have you tried a different compiler? – rici Dec 01 '18 at 18:13
  • ... I ask because I tried to reproduce the issue with gcc and was unable to do so. However, it would really help if you could edit your question to include a [mcve], because without that, trying to reproduce the problem is 95% guesswork. – rici Dec 02 '18 at 01:04

1 Answers1

1

Usually, in all the projects I've worked I have seen it done this way.

Create a file myerror.h:

#ifndef _MYERROR_H__
#define _MYERROR_H__

#ifdef __cplusplus
extern "C" {
#endif

typedef enum errors {
    OK,
    BADERROR,
    LASTENUM
} ERR;

extern const char *err_msg(ERR err);

#ifdef __cplusplus
} // extern C
#endif

And then a file myerror.cpp:

#include "myerror.h"

static const char *_errtext[] = {
    "OK",
    "BADERROR",
    "LASTENUM"
};

const char* err_msg(ERR error){
    return _errtext[error];
}

That way you just have to include myerror.h from all the files you want and call err_msg(error) whenever you want to print the error in text format. So in another file you'd have:

#include "myerror.h"
int method(){
    ERR whatever = OK;
    std::cout << err_msg(whatever);
    ... // Some other stuff here
}

I'm not sure why you want it done in the same file, but as I said, this is how I usually see it done.

lpares12
  • 3,504
  • 4
  • 24
  • 45
  • I understand your solution with myerror.h and myerror.cpp. I am trying to put BOTH sets of information in the SAME FILE to prevent any possibility that the two pieces of code can become misaligned. This is an engineering issue of protecting the information from error. The comment about using a different compiler is of no help. Yes I believe that this use of conditional compile DOES WORK in gcc. It should work with any compliant compiler. Any alternative to my attempted solution that can achieve the goal of keeping this source aligned (in any compiler) will be much appreciated. – frankevans Dec 03 '18 at 16:30