如何避免来自C中#define的名称冲突?(或 C++) [英] how to avoid name conflicts coming from #define in C? (or C++)

查看:92
本文介绍了如何避免来自C中#define的名称冲突?(或 C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是非常基本的问题,我可以通过更改一些名称来避免这种情况,但我认为这里可能缺少一些东西.
我为这个问题做了一个最简单的代码.

This should be very basic question, and I can avoid this situation by changing some names but I think maybe there is something I am missing here.
I have made a simplest code for this problem.

conv.h :
  1 struct convpar_ {
  2 int K;
  3 } convpar_;

test.c :
  1 #include <stdio.h>
  2 #include "conv.h"
  3 
  4 #define K 7
  5 
  6 typedef struct convpar_ convpar;
  7 
  8 void func1(convpar cp)
  9 {
 10 printf("cp.K = %d\n", cp.K);
 11 }
 12 
 13 main()
 14 {
 15 convpar cp = {K};
 16 
 17 func1(cp);
 18 }

如果我做cc test.c -o test,我得到

cc     test.c   -o test
test.c: In function 'func1':
test.c:13: error: expected identifier before numeric constant

我知道这是因为我在第 4 行将字符 'K' 定义为 '7',这使得第 10 行出现 printf("cp.7" = %d\n", cp.7); 预处理后.当我将 convpar_ 的成员 K 的名称更改为其他名称(例如 Ki)时,此问题就消失了.

I know this is because I defined character 'K' as '7' in line 4 and this makes line 10 appear printf("cp.7" = %d\n", cp.7); after preprocessing. When I change the name of convpar_'s member K to something else(ex. Ki), this problem goes away.

但有时,当我想定义一个常量并且它恰好是我在定义变量的同一个文件中使用的全局变量的名称或结构的成员变量时,有时会出现类似的情况.解决这个问题的正确方法是什么?(这也适用于 C++)

But at times, there are cases like it here when I want to define a constant and it happens to be a name of a global variable or a member variable of a struct I use in the same file I defined the variable in. What is the right approach to solve this problem? (this also applies to C++)

推荐答案

您无法解决此问题,因为这是预处理器的目标:即时修改您的代码.解决方案是采用良好的编码实践:不要将预处理器用于一般编程.此外,对命名空间使用命名规则.什么?将其命名为 CONVERSION_ID_K、CONVERSION_ID_L,依此类推.变量等使用小写.

You cannot work around this because that's the preprocessor goal: modifying your code on the fly. The solution is to adopt good coding practices: don't use the preprocessor for general programming. Also, use a naming discipline with namespaces. K what ? Name it CONVERSION_ID_K, CONVERSION_ID_L, and so on. Use lower case for variables, etc.

这篇关于如何避免来自C中#define的名称冲突?(或 C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆