¿Cómo definir macros?

He radius2 = x*x +y*y + z*z.

I want to switch 3D to 2D (i.e. radius2 = x*x + y*y) without deleting z*z.

I tried to define a macro

1.h [header file to switch 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 Principal

#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);
}

When I compile I get this error:

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

preguntado el 01 de febrero de 12 a las 04:02

2 Respuestas

@mmodahl's answer explains why your definition of EXPAND no se encuentra.

BTW, it would be more straightfoward to perform the calculation in the macro:

#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

Note the extra parentheses, which are there in case an expression is passed in as one of the parameters.

Respondido 01 Feb 12, 08:02

//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

Since you have to toggle only between 2 cases, simply define a macro with appropriate name as shown. The comparison as shown in your code doesn't work during preprocessing stage.

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.