Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TUTORIAL02: 用于debug enum的宏 #50

Closed
randawn opened this issue Oct 13, 2016 · 2 comments
Closed

TUTORIAL02: 用于debug enum的宏 #50

randawn opened this issue Oct 13, 2016 · 2 comments

Comments

@randawn
Copy link

randawn commented Oct 13, 2016

@miloyip
您好,
我在test.c里面加了两条用于DEBUG的宏。

test.c

#define EXPECT_EQ_RET(expect, actual) EXPECT_EQ_BASE((expect) == (actual), ret_e_name[expect], ret_e_name[actual], "%s")
#define EXPECT_EQ_TYPE(expect, actual) EXPECT_EQ_BASE((expect) == (actual), type_e_name[expect], type_e_name[actual], "%s")

然后把enum对应的名称数组放在了leptjson.h里面

leptjson.h

static const char* ret_e_name[] = {  
    "LEPT_PARSE_OK",
    "LEPT_PARSE_EXPECT_VALUE",
    "LEPT_PARSE_INVALID_VALUE",
    "LEPT_PARSE_ROOT_NOT_SINGULAR",
    "LEPT_PARSE_NUMBER_TOO_BIG"
};
static const char* type_e_name[] = {
    "LEPT_NULL",
    "LEPT_FALSE",
    "LEPT_TRUE",
    "LEPT_NUMBER",
    "LEPT_STRING",
    "LEPT_ARRAY",
    "LEPT_OBJECT"
};

我有一个疑问:

  1. 如果我加了static char* ret_e_name[] = ...,编译器会warn: var defined but not used(虽然现在没用use,但是以后可能会)。
  2. 如果直接写char* ret_e_name[] = ...,因为leptjson.h被两个文件同时include,LINK的时候会报错redefine。

我在想难道1就是正确的做法吗?通过编译选项把warning去掉?
我总感觉有其他漂亮的办法,希望您能解答。

@miloyip
Copy link
Owner

miloyip commented Oct 13, 2016

在头文件定义变量是不好的。

建议写成函数形式:

const char* lept_get_error_name(int error) {
    static const char* error_name[] = ... ;
    assert(error >= 0 && error < ...);
    return error_name[error]
}

@randawn
Copy link
Author

randawn commented Oct 13, 2016

哦 谢谢。
这应该就是best practice.
可以close掉了。

@randawn randawn closed this as completed Oct 13, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants