简体   繁体   English

在C语言的函数标头(声明/定义)中使用#define预处理程序指令可以吗?

[英]Is it OK to use #define preprocessor directive for function header (declaration/definition) in C?

I'm currently working on some project as a C Developer in a company, and in our code there are many large function declarations for a different types of handling (such as state machine callbacks, event callbacks, timers etc.) and every type of handler declaration has the same semantics, for example event handler: static void onEvent1(Event event, EventArgs *args); 我目前正在一家公司中担任C开发人员的某个项目,在我们的代码中,有许多用于不同类型处理(例如状态机回调,事件回调,计时器等)的大型函数声明,以及每种类型的处理程序声明具有相同的语义,例如事件处理程序: static void onEvent1(Event event, EventArgs *args); .

There can be very big amount of such handlers and with many parameters in brackets, so I've decided to replace it with a small macro to increase readability and ease code writing like this: #define EVENT_HANDLER(funcName) static void funcName(Event event, EventArgs *args) 此类处理程序可能非常多,方括号中包含许多参数,因此我决定将其替换为一个小的宏,以提高可读性并简化如下代码的编写: #define EVENT_HANDLER(funcName) static void funcName(Event event, EventArgs *args)

So the example code would look like this: 因此,示例代码如下所示:

without #define : 没有#define

static void onEvent1(Event event, EventArgs *args);
static void onEvent2(Event event, EventArgs *args);
static void onEvent3(Event event, EventArgs *args);

with #define : 与#define

EVENT_HANDLER(onEvent1);
EVENT_HANDLER(onEvent2);
EVENT_HANDLER(onEvent3);

After I've added changes to a code with such macro, I've heard a lot of critics from my colleagues in my address with no clear reason why it is not good. 在使用此类宏向代码中添加更改后,我在我的讲话中听到了很多同事的批评,没有清楚为什么不好的原因。 I've googled for an answer, and as far as I understand, such text replacing macro can do no harm nor lower code understanding. 我已经在谷歌上寻找答案,据我所知,这样的文本替换宏不会造成损害,也不会降低代码理解度。 So, can somebody bring a clarity to me: is it really a bad habit to use #define in such a way, or no, and most impornantly: WHY? 因此,有人可以给我一个清晰的提示:以这种方式使用#define真的是个坏习惯,还是不,而且最无能为力:为什么?

thanks) 谢谢)

You can just use a regular typedef to be type safe. 您可以只使用常规的typedef来保证类型安全。 It avoids the pitfalls of the pre-processor and doesn't require inventing your own language within a language. 它避免了预处理程序的陷阱,并且不需要在一种语言中发明自己的语言。 Your colleagues have a point. 您的同事有一点。

typedef void EventCB(Event, EventArgs *);

And use it as you'd expect: 并按预期使用它:

static EventCB onEvent1;
static EventCB onEvent2;
static EventCB onEvent3;

You'll need to repeat the prototype when defining the functions, but the compiler will do type checking and warn you of any mistakes. 定义函数时,您需要重复原型,但是编译器将进行类型检查并警告您任何错误。 Another plus of working with the type system, is the ability to use the same type to declare pointers: 使用类型系统的另一个好处是可以使用相同的类型来声明指针:

EventCB *func_ptr = &onEvent1;

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

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