简体   繁体   English

const静态数组的条件编译

[英]Conditional Compile of const static arrays

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: 我有一个包含以下内容的system.cpp文件:

#define SYSTEMCODE
#include "myerrors.h"

The file myerrors.h contains: 文件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

I include system.h in all sources that need error services and they do not define SYSTEMCODE. 我将system.h包含在所有需要错误服务的资源中,并且未定义SYSTEMCODE。

I expect that only the system.cpp file will compile the text array and all others will simply have an extern reference. 我希望只有system.cpp文件会编译文本数组,而所有其他文件都将仅具有外部引用。 The system.cpp object does not have the _errtext array thus causing a link error. system.cpp对象没有_errtext数组,因此导致链接错误。 I disable pre-compiled headers and I have tried many variations of this. 我禁用了预编译的头文件,并且已经尝试了许多变体。 MSDEV does not get it right. MSDEV无法正确处理。

Any ideas? 有任何想法吗?

Usually, in all the projects I've worked I have seen it done this way. 通常,在我工作过的所有项目中,我都看到过这种方式。

Create a file myerror.h : 创建一个文件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 : 然后是一个文件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. 这样,您只需要从所有想要的文件中包含myerror.h ,并在每次要以文本格式打印错误时调用err_msg(error)即可。 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. 我不确定为什么要在同一文件中完成此操作,但是正如我所说,这是我通常看到的完成方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM