【问题标题】:How to define macros?如何定义宏?
【发布时间】:2012-02-01 04:04:31
【问题描述】:

我有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

ma​​in.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

【问题讨论】:

    标签: c macros compiler-errors


    【解决方案1】:

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

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

    #if 尺寸 == 2 #define COMPUTE_RADIUS(a,b,c) ((a)*(a) + (b)*(b)) #elif 尺寸 == 3 #define COMPUTE_RADIUS(a,b,c) ((a)*(a) + (b)*(b) + (c)*(c)) #万一

    注意额外的括号,以防表达式作为参数之一传入。

    【讨论】:

      【解决方案2】:
      //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 一个具有适当名称的宏,如图所示。您的代码中显示的比较在预处理阶段不起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 2012-09-07
        • 1970-01-01
        相关资源
        最近更新 更多