2012-02-01 66 views
-1

我有radius2 = x*x +y*y + 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 

主。 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); 
} 

當我編譯我得到這個錯誤:既然你已經如圖所示切換之間只有2例,只是define用適當的名稱宏

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

回答

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 

。代碼中顯示的比較在預處理階段不起作用。

2

@ mmodahl的回答解釋了爲什麼您的EXPAND的定義沒有找到。

順便說一句,這將是更straightfoward在宏執行計算:

 
#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 

注額外的括號,這是存在的情況下表達被傳遞在作爲參數之一。