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?

4

1 回答 1

1

通常,在我工作过的所有项目中,我都看到它是这样完成的。

创建一个文件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

然后是一个文件myerror.cpp

#include "myerror.h"

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

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

这样,您只需包含所有您想要的文件,并在您想以文本格式打印错误时myerror.h调用。err_msg(error)因此,在另一个文件中,您将拥有:

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

我不确定你为什么要在同一个文件中完成它,但正如我所说,这就是我通常看到的完成方式。

于 2018-12-01T18:52:45.267 回答