[英]Conditional Compile of const static arrays
我正在尝试创建一个错误枚举,并将关联的文本描述符对齐在同一文件中。 我有一个包含以下内容的system.cpp文件:
#define SYSTEMCODE
#include "myerrors.h"
文件myerrors.h包含:
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
我将system.h包含在所有需要错误服务的资源中,并且未定义SYSTEMCODE。
我希望只有system.cpp文件会编译文本数组,而所有其他文件都将仅具有外部引用。 system.cpp对象没有_errtext数组,因此导致链接错误。 我禁用了预编译的头文件,并且已经尝试了许多变体。 MSDEV无法正确处理。
有任何想法吗?
通常,在我工作过的所有项目中,我都看到过这种方式。
创建一个文件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
}
我不确定为什么要在同一文件中完成此操作,但是正如我所说,这是我通常看到的完成方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.