how to avoid name conflicts coming from #define in C? (or C++)

一曲冷凌霜 提交于 2020-01-17 06:03:10

问题


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 }

If I do cc test.c -o test, I get

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

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.

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++)


回答1:


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.



来源:https://stackoverflow.com/questions/43883432/how-to-avoid-name-conflicts-coming-from-define-in-c-or-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!