Normaly if I make a small code snipet, I usually put it in a whathever.c – file. From the C-file I include a .h -file with other includes or some global varaibles.
I’ve just heard that the compiler makes the code in a header faster, or somtehing I would love if someone could explain or comment this.
Example code in a header instead of a c-file (could be in a c) ->
#define PWM_INTERRUPT \
void InterruptHook(void) \
{ \
PR4 ^= _SoftPWM_Toggle; \
\
PIR3bits.TMR4IF = 0; \
\
_asm \
INCF PR4,0,ACCESS \
CPFSLT TMR4,ACCESS \
_endasm \
\
/* if(TMR4 > PR4) */ \
PIR3bits.TMR4IF = 1; \
\
SOFT_PWM_PIN ^= 1; \
\
_asm \
RETFIE 1 \
_endasm \
}
You can’t put a macro in a separate .c file, because macros are handled by the preprocessor, which is the first step in the compilation process, and separate .c files are handled in the link stage, which is the last step.
Using a macro instead of a function might be faster, because it avoids the overhead of a function call. However, it will slow your compiles down because it compiles the same code multiple times. It will make your code larger because of redundant copies. If caching is an issue, it might actually run slower because of repeatedly fetching different redundant copies into cache. There’s no way to know for sure without profiling.
If you’re talking about the difference between putting a macro in the same .c file and a header file, there’s no difference performance-wise. You just would have to copy and paste it into every .c file that uses it.