The used attribute is useful in situations where you want to force the compiler to emit a character, when you can usually omit it. As the GCC Documentation says (my attention):
This attribute, attached to a function, means that the code must be emitted for the function, even if it turns out that the function is not a link. This is useful, for example, when a function refers only to an inline assembly .
For example, if you have code like this:
you may notice that the foo character is present with the -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 inside 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)
so now foo can be referenced inside it.
You may also have noticed that the gcc warning has now disappeared since you told the compiler that you were sure that foo actually being used "behind the scenes".
source share