What is the gcc attribute utility?

#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; } 

Why do I need it?

Is there any way to achieve xyz some way other than directly calling a function, for example, some dlsym() like magic?

+7
source share
2 answers

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:

 #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 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".

+9
source

A specific use case is for interrupt routines in a static library. For example, timer overflow interrupt:

void __attribute__((interrupt(TIMERA_VECTOR),used)) timera_isr(void)

This timera_isr is never called by any function in user code, but it can be an essential part of the library. To ensure that it is connected and that there is no interrupt vector pointing to an empty section, the keyword ensures that the linker does not optimize it.

0
source

All Articles