Help understanding how compilers treat inline functions

Discussion in 'Programmer's Corner' started by danielb33, Sep 30, 2012.

  1. danielb33

    Thread Starter Member

    Aug 20, 2012
    105
    0
    First, thank you experts for taking the time to help me. You are helping me make it through my first internship.

    I am reading all over about how inline functions have certain restrictions and properties and that sometimes compilers will ignore the inline function command and treat the inline function as a normal function. I do not understand why and where this happens even after reading much. Generally, the only time I will want to use an inline function is if I want to eliminate the function all together. Apparently, this is only done if "all the calls are know, i.e. are placed in the same source file as the function." I do not understand this. So I cannot make an inline function in init.c and call it in main.c???? Also, I keep reading that if the purpose is only to remove the function completely, "the inline function should be marked as "static inline" rather than just inline, so that it cannot be seen from other files. Otherwise the function will have to be kept (even though it might still be inlined at some calls), and we rely on the liner to remove it if it is no called." Can someone explain this more? I greatly appreciate your help!
     
  2. WBahn

    Moderator

    Mar 31, 2012
    17,715
    4,788
    Basically, at least in C, flagging a function as inline is nothing more than a hint and a suggestion to the compiler asking it to, if possible, inline the function. The compiler is under no obligation to do so. I'll go out on a limb and speculate that a compiler could even not have the capability of inlining a function and still be considered compliant - again, that's speculation on my part.

    Files are compiled one at a time to produce object files and then linked together later. So if you have function fred() definition in one file and only the function declaration (i.e., prototype) visible when compiling another file that has calls to fred() in it, the compiler can't inline those calls, it only has enough information to construct a function call to fred().

    Within the file in which fred() is defined, the compiler has to assume that the function might be called from other files, hence it will have to construct the code for the function anyway. If it's already done that, then it might opt to go ahead and just use function calls even for calls within that file, although it might inline that code. But if you define the function as being static, then the compiler knows that it is NOT visible outside that file and, hence, it doesn't have to generate the function code at all if it can inline all of the calls made within the file.
     
  3. danielb33

    Thread Starter Member

    Aug 20, 2012
    105
    0
    Ahhh I get it! Thanks so much!
     
Loading...