簡體   English   中英

const靜態數組的條件編譯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM