c++cgccclangicc

What's the usecase of gcc's used attribute?


#include <stdio.h>

// xyz will be emitted with -flto (or if it is static) even when
// the function is unused

__attribute__((__used__))
void xyz() {
  printf("Hello World!\n");
}

int main() {
  return 0;
}

What do I need this for?

Is there any way I could still reach xyz somehow besides directly calling the function, like some dlsym() like magic?


Solution

  • Attribute used is helpful in situation when you want to force compiler to emit symbol, when normally it may be omitted. As GCC's documentation says (emphasis mine):

    This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

    For instance, if you have code as follows:

    #include <iostream>
    
    static int foo(int a, int b)
    {
        return a + b;
    }
    
    int main()
    {
       int result = 0;
    
       // some inline assembly that calls foo and updates result
    
       std::cout << result << std::endl;
    }
    

    you might notice, that no symbol foo is present with -O flag (optimization level -O1):

    g++ -O -pedantic -Wall check.cpp -c
    check.cpp:3: warning: ‘int foo(int, int)’ defined but not used
    nm check.o | c++filt | grep foo
    

    As a result you cannot reference foo within this (imaginary) inline assembly.

    By adding:

    __attribute__((__used__))
    

    it turns into:

    g++ -O -pedantic -Wall check.cpp -c
    nm check.o | c++filt | grep foo
    00000000 t foo(int, int)
    

    thus now foo can be referenced within it.

    You may also have spotted that gcc's warning is now gone, as you have tell you compiler that you are sure that foo is actually used "behind the scene".