Home > Back-end >  [[maybe_unused]] for a function
[[maybe_unused]] for a function

Time:08-16

I don't quite understand when [[maybe_unused]] on a function itself could be useful.

By reading the paper, it only said the attribute may be applied to the declaration of a function. My question is that if it implies compiler will raise warning on an unused function, then for any public header of a library, everything should have the attribute to avoid warning as users might only use parts of the library.

Is my understanding correct?

Thank you.

CodePudding user response:

Inspired from here:

namespace {
    [[maybe_unused]] void foo() {}
    void bar() {}
}

int main() {}

Functions declared in the unnamed namespace can only be used in this translation unit, hence the compiler can warn when the functions are not used. And indeed gcc warns for bar (error because of -Wall -Werror) but due to [[maybe_unused]] not for foo :

<source>:5:10: error: 'void {anonymous}::bar()' defined but not used [-Werror=unused-function]
    5 |     void bar() {}
      |          ^~~

Live

The original example in the page linked above is a little more motivating, as it uses conditional compilation where depending on some symbols being set a function is used or not.

CodePudding user response:

The compiler warns about functions that it can tell are unused. If it is unsure - if your function ends up in a place where others could call it, like in a library - the compiler assumes it is used.

For example, if you have a translation unit with these functions (ref):

int square(int num) {
    return num * num;
}

static int cube(int num) {
    return num * num * num;
}

square could be called by other functions from other translation units. It's unused here but may be used somewhere else. The compiler doesn't know about these other places, so it cannot flag the function as unused. There is no warning; adding the attribute has no effect.

cube, on the other hand, is static - so if it's used anywhere, it must be in this translation unit. Since it isn't used here, the compiler (at least gcc with -Wunused-function) warns about this.

Adding [[maybe_unused]] to cube then silences that warning. It basically says "I know that you know that this is unused; don't warn about it."

  •  Tags:  
  • c
  • Related