gcc warning: function used but not defined

后端 未结 3 1889
鱼传尺愫
鱼传尺愫 2021-02-04 03:13

I am getting the warning: function used but not defined. I have static __inline__ in header file say a.h. The header file is included in <

3条回答
  •  攒了一身酷
    2021-02-04 03:50

    Functions declared static within a .c file are only visible/usable within that file only. If they are not used in it, then they are effectively dead code and the compiler warns you about this fact. In GCC you can use the unused function attribute to suppress this warning:

    static int __attribute__((unused)) function1() {
    ...
    }
    

    EDIT:

    In general you should usually follow the following guidelines regarding inline functions:

    • If they are used in multiple C files, declare them static and have their definition in an included header file. That allows all .c files that include that header to have their own private definition of the function, which allows the compiler to inline it. Lone static function prototypes make little to no sense in a header file that will be used by multiple source files, since their actual definitions will be missing.

    • If they are not intended to be reused, have their definition (and, if necessary, their prototype) in the .c file where they are supposed to be used.

    If GCC complains about being unable to inline a function, due to the function size:

    • Ask yourself if you really need that function to be inlined - from my experience, the compiler usually knows best.

    • If you really, really want that function inlined, the always_inline function attribute may be of use. You may also have to provide a non-default -finline-limit=n option to GCC to increase the allowed size for inline functions.

    See also this for additional information on inline functions and some possible pitfalls regarding their use.

    EDIT 2:

    If you have a static inline function defined in a shared header file and want to turn it into a normal, for lack of a better word, function you should:

    • Select a .c file where the presence of that function make sense (i.e. put it with other related functions).

    • Remove the static and inline keywords from its definition and move the definition from the header into that file.

    • Remove the static and inline keywords from its prototype and put it into the header file.

    Congratulations, you now have a normal publicly-available function.

    Disclaimer: you just made a function that was private to a number of files, public to all of your program. If there is another public symbol - variable or function - with the same name, you may get errors while linking or even strange behaviour at runtime. You've been warned...

提交回复
热议问题