Simple C inline linker error

前端 未结 3 540
轮回少年
轮回少年 2020-12-06 12:28

simple problem:

given the following program:

#include 

inline void addEmUp(int a, int b, int * result)
{
    if (result) {
        *r         


        
相关标签:
3条回答
  • 2020-12-06 12:59

    Try adding the "-O" option to your compiler command. Inlining is turned on only when optimization is enabled.

    0 讨论(0)
  • 2020-12-06 13:04

    Paragraph 7 of section 6.7.4 says:

    Any function with internal linkage can be an inline function. For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit. If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.

    Your file does not contain an external definition of addEmUp, and the compiler chose to use the external definition in the call in main.

    Provide an external definition, or declare it as static inline.

    0 讨论(0)
  • 2020-12-06 13:15

    The program causes undefined behaviour (no diagnostic required) due to 6.9/5, sometimes informally called the "one definition rule":

    If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.

    Your program uses the identifier addEmUp while providing no external definition for it. (As mentioned already, "An inline definition does not provide an external definition for the function").

    We do not need to start talking about which definition a function call calls etc. etc. The reason for ODR violations being undefined with no diagnostic required is to make it easier on the compiler writer; if this code required a diagnostic then the compiler would have to do a pass with inline optimization disabled to check for the existence of the external definition, which is a waste of time really.

    0 讨论(0)
提交回复
热议问题