Search code examples
cgccinline

Behaviour of 2 inline functions calling each other in C


I am in the process of trying to learn C's more advanced aspects and wrote this when experimenting with the __inline__ keyword:

#include <stdio.h>


void f(int);
void g(int);


__inline__ void f(int egg)
{
    printf("f %d\n", egg);
    g(egg);
}


__inline__ void g(int egg)
{
    printf("g %d\n", egg);
    f(egg);
}


int main()
{
    f(123);

    return 0;
}

I went to the GNU manuals and found that the -Winline compiler option warns when a function marked __inline__ can't be substituted.

I was indeed expecting a warning, but I compiled this program with gcc -ansi -pedantic -Wall -Wextra -Winline -o test test.c and there were no warnings.

When I ran the program, it printed out the number a whole bunch of times before a segmentation fault, presumably due to the recursion limit being exceeded.

My question is, how does gcc behave in cases like that? If it does inline the functions, how does it know it hit a recursive call between two functions?

Thank you in advance


Solution

  • https://gcc.gnu.org/onlinedocs/gcc-7.4.0/gcc/Inline.html#Inline

    GCC does not inline any functions when not optimizing unless you specify the ‘always_inline’ attribute for the function

    Since you are compiling without optimization, gcc does not even try to inline your functions, hence you do not get a warning that it wasn't done.

    When I compile your code with -O -Winline, I get a warning as expected:

    inline.c: In function ‘main’:
    inline.c:8:17: warning: inlining failed in call to ‘f’: call is unlikely and code size would grow [-Winline]
     __inline__ void f(int egg)
                     ^
    inline.c:24:5: note: called from here
         f(123);
         ^~~~~~