inline a function as needed - c

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi guys

I want to write a function that can be used in the main program and/or in interrupt. So my question is, can I write the function once, but only inline the function in interrupt?

Code:
uint8_t foo(uint8_t data);

uint8_t foo(uint8_t data){
    // do stuff
}

void main(void){
    while(1){
       foo(data);  // do not inline here
       // other stuff
    }
}

INTERRUPT_ISR(void){
    if(ISR_FLAG){
        inline foo(data);  // inline here
    }
}
 

Papabravo

Joined Feb 24, 2006
21,228
You can, but doing so has inherent dangers. If I were you I would have identical code in two separate functions neither one of which cares if interrupts are enabled or not. Use one of them in the interrupt section, and use the other one in the non-interrupt code. Make sure you don't "shoot yer eye out" by allowing both functions to reference the SAME global variable(s)
 

WBahn

Joined Mar 31, 2012
30,088
Also, at least in hosted code, the inline attribute is only a suggestion to the compiler. It always has the option to inline a function and it does not have to inline a function you want it to.

If you REALLY want the function inlined, then write it as a parameterized macro.
 

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Also, at least in hosted code, the inline attribute is only a suggestion to the compiler. It always has the option to inline a function and it does not have to inline a function you want it to.

If you REALLY want the function inlined, then write it as a parameterized macro.
you mean something like these??
Code:
#define foo()    do{code_1; code_2; code_3;}while(0);
 

Thread Starter

bug13

Joined Feb 13, 2012
2,002
You can, but doing so has inherent dangers. If I were you I would have identical code in two separate functions neither one of which cares if interrupts are enabled or not. Use one of them in the interrupt section, and use the other one in the non-interrupt code. Make sure you don't "shoot yer eye out" by allowing both functions to reference the SAME global variable(s)
Writing two identical function seem like a good idea. But I do intend to access the same global variable(s), ooops! I guess I can always disable interrupt for a short time in the function used outside a interrupt while access the same global variable(s).
 

WBahn

Joined Mar 31, 2012
30,088
you mean something like these??
Code:
#define foo()    do{code_1; code_2; code_3;}while(0);
If that's what you need, then you wouldn't need a parameterized macro.

But the foo() you gave in your initial code snippet used a parameter, so your macro would need to as well.

If you function returns a value as well as containing things like loops and such, then making the code inlineable can be easier said than done -- which is why the inline modifier is only a suggestion to the compiler.
 
Top