I found the code below in a project and I'm having problems understanding why GCC doesn't complaint since dlc is called before it has been defined.
#define CAN_SET_DLC(dlc) (CANCDMOB |= (dlc))
typedef struct
{
uint8_t mob_n;
uint8_t handle;
long id;
long id_msk;
uint8_t dlc;
uint8_t data_pt[8];
uint8_t status;
} can_msg;
¿The variable type of dlc should also be defined?:
define CAN_SET_DLC(uint8_t dlc) (CANCDMOB |= (dlc))
CodePudding user response:
The preprocessor has no knowledge of variables or any language construct. It is just a token processor.
In #define a(b) ( b 1 )
this means that anytime the preprocessor encounters a(foo)
in the source text, it will replace it with ( foo 1 )
. Then the compiler will check whether it is correct C.
CodePudding user response:
This is the normal way to define macro with arguments: https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html#Macro-Arguments
Macros just replace text basically so you have to take care about variable type.
CodePudding user response:
No, macros only substitute text (more precisely tokens) and it is done before actual C code compilation. The preprocessor does not know anything about C language.
The preprocessed source code then is compiled by the C compiler.
#define CAN_SET_DLC(dlc) ((DLC) |= CANCDMOB)
#define CANCMOB 0x34
int foo(uint8_t z)
{
CAN_SET_DLC(z);
return z;
}
will result in
int foo(uint8_t z)
{
((z) |= 0x34);
return z;
}