如何定义宏?

时间:2012-02-01 04:04:32

标签: c macros compiler-errors

我有radius2 = x*x +y*y + z*z

我想在不删除z * z的情况下将3D切换为2D(即radius2 = x*x + y*y)。

我试图定义一个宏

1.h [切换2D / 3D的头文件]

 #define DIMENSIONS 2 //or, 3

2.H

#if DIMENSIONS == 2
#define EXPAND(a,b,c) a, b
#endif
#if DIMENSIONS == 3
#define EXPAND(a,b,c) a, b, c
#endif

的main.c

#include "stdio.h"
#include "1.h"
#include "2.h"

main(){
int x, y, z, radius2;
x = 2;
y = 3; 
z = 4;
radius2 = EXPAND(x*x, +y*y, +z*z);
printf("%d", radius2);
}

编译时我收到此错误:

Undefined symbols:
 "_EXPAND", referenced from:
     _main in ccsC4tfr.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

2 个答案:

答案 0 :(得分:2)

@ mmodahl的回答解释了为什么找不到EXPAND的定义。

顺便说一下,在宏中执行计算会更直接:

#if DIMENSIONS == 2
#define COMPUTE_RADIUS(a,b,c) ((a)*(a) + (b)*(b))
#elif DIMENSIONS == 3
#define COMPUTE_RADIUS(a,b,c) ((a)*(a) + (b)*(b) + (c)*(c))
#endif

请注意额外的括号,如果表达式作为参数之一传入,则会出现这些括号。

答案 1 :(得分:0)

//1.h
#define DIMENSIONS_2
...
//2.h
#ifdef DIMENSIONS_2
#define EXPAND(a,b,c) a, b
#else
#define EXPAND(a,b,c) a, b, c
#endif

由于您只需要在两种情况之间切换,只需define一个具有适当名称的宏,如图所示。您的代码中显示的比较在预处理阶段不起作用。