问题
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