C preprocessor directive problem

  • Thread starter Thread starter handsomecat
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
handsomecat
Messages
68
Reaction score
0
In the main body of my code i have something like this:

Code:
Cmin_vec[1][1][1] = rptr->cmin[3];

I want to replace this with a macro

Code:
#define COPY_CMIN( cmin, rptr)  (cmin)[1][1][1] = (rptr)->cmin[3]

and call it in from my code

Code:
COPY_CMIN( Cmin_vec, rptr)

But i get the error message saying "structure has no member named `Cmin_vec'.

how should I go about doing it?
 
Physics news on Phys.org
handsomecat said:
I want to replace this with a macro
Code:
#define COPY_CMIN( cmin, rptr)  (cmin)[1][1][1] = (rptr)->cmin[3]
and call it in from my code
Code:
COPY_CMIN( Cmin_vec, rptr)
This expands to
Code:
(Cmin_vec)[1][1][1] = (rptr)->Cmin_vec[3]

If you wan't to preserve that cmin[3] on the right-hand side then you must not use cmin as one of the macro argument names. The macro processor replaces all occurrences of a macro parameter in the macro definition text with the corresponding argument value. The expansion is not limited to parameters in parentheses. The preprocessor just sees those parentheses as part of a string.
 
If you want to see macro expansions, the compiler often has an option to let you see input from the "cpp" phase of pre-compilation.
Code:
[g]cc -E myfile.c
will do that. Check your compiler docset or a man page.
You can also invoke cpp on some UNIX systems directly.
Make sure the command "which cpp" is able to find the executable image, then try:
Code:
cpp myfile.c

Note that you cannot debug code in a debugger when the code is inside a macro.
 
Warren -

Macros are evil? Is this like void main()? I don't think so. Try reading the the Linux kernel source or the macros that the C standard defines. Macros cause problems when used in a problematic way; the OP's example falls into that category.
 
The vast majority of programmers are not skilled enough to properly use macros, or to easily solve the often mystifying bugs they cause. They're just not a good idea. There's almost always a better way.

- Warren