Example of a weak reference
A library contains a function
foo(), that is called in some builds of an
application but not in others. If it is used,
init_foo() must be called
first. You can use weak references to automate the call to
The library can define
foo() in the same
ELF section. The application initialization code must call
weakly. If the application includes
foo() for any reason, it also includes
init_foo() and this is called from the initialization code. In any builds
that do not include
foo(), the call to
removed by the linker.
Typically, the code for multiple functions
defined within a single source file is placed into a single ELF section by the compiler.
However, certain build options might alter this behavior, so you must use them with caution
if your build is relying on the grouping of files into ELF sections:
The compiler command-line option
--split_sections results in each function being placed in its own section.
In this example, compiling the library with this option results in
placed in separate sections. Therefore
not automatically included in the build due to a call to
The linker feedback mechanism,
init_foo() as being
unused during the link step. This causes the compiler to place
init_foo() into its own section during subsequent compilations, so that it
can be removed.
The compiler directive
section also instructs the compiler to generate a separate ELF section for
In this example, there is no need to rebuild the initialization code between builds that
foo() and do not include
foo(). There is also no
possibility of accidentally building an application with a version of the initialization
code that does not call
init_foo(), and other parts of the application that
An example of foo.c source code that is typically built into a library
// Some initialization code
// A function that is included in some builds
// and requires init_foo() to be called first.
An example of init.c is:
__weak void init_foo(void);
// Rest of code that may make calls to foo() directly or indirectly.
An example of a weak reference generated by the assembler is:
IMPORT init_foo WEAK
AREA init, CODE, readonly
;Rest of code