简体   繁体   中英

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:

#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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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