mihkhub / gtoolchain-in-action

GNU toolchain in action
0 stars 0 forks source link

Declaring Attributes of Functions #4

Open mihkhub opened 6 years ago

mihkhub commented 6 years ago

In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully.

The keyword __attribute__ allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses.

mihkhub commented 6 years ago
constructor
destructor
constructor (priority)
destructor (priority)

The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () completes or exit () is called.

Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.

So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see Section 7.7 [C++ Attributes], page 671).

mihkhub commented 6 years ago
deprecated
deprecated (msg)

The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead.

mihkhub commented 6 years ago
ifunc ("resolver")

The ifunc attribute is used to mark a function as an indirect function using the STT GNU IFUNC symbol type extension to the ELF standard.

mihkhub commented 6 years ago
section ("section-name")

Normally, the compiler places the code it generates in the text section. Sometimes, however, you need additional sections, or you need certain particular functions to appear in special sections. The section attribute specifies that a function lives in a particular section. For example, the declaration:

extern void foobar (void) __attribute__ ((section ("bar")));

puts the function foobar in the bar section.

Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.