ARM Technical Support Knowledge Articles

Why does the linker select weak definitions instead of non-weak ones from a library?

Applies to: DS-5, RealView Development Suite (RVDS)

Answer

In the attached example, the function foo() marked with the __weak keyword from the static library lib.a is selected by the armlink.  This is expected linker behaviour.

obj1.o : 
    __weak void foo() {};

obj2.o:
    void foo() {};

test.o:
    void bar() {foo();} 

lib.a: armar –-create=lib.a obj1.o obj2.o

armlink main.o lib.a –o test.axf –-verbose

=========================
Loading object main.o.
        :
        definition: main
        reference : foo
        : 
Selecting member obj1.o(lib.a) to define foo.
Loading member obj1.o from lib.a.
        weak defn : foo
=========================

The reason why the foo() function marked with __weak from obj1.o is selected instead of the non-weak foo() function, is because of the linker's symbol selecting rules used for libraries and also the ordering of the input objects when creating the library with armar.

The linker will only search through libraries to resolve a reference if it cannot resolve that reference after searching all input objects. If required, the libraries are searched from left to right according to their position on the linker command line.  Objects within the library will be searched by the order in which they were archived.  As soon as armlink finds a symbol match for the reference, the searching is finished, even if it matches a weak definition.

The ELF ABI section 4.6.1.2 says:

"A weak definition does not change the rules by which object files are selected from libraries. However, if a link set contains both a weak definition and a non-weak definition, the non-weak definition will always be used."

The "link set" is the set of objects that have been loaded by the linker. It does not include objects from libraries that are not required.

Therefore archiving two objects where one contains the weak definition of a given symbol and the other contains the non-weak definition of that symbol, into a library or separate libraries, is not recommended.  There are different ways to guarantee armlink selecting a non-weak version of a given symbol:

References:

Attachments: test_weak.zip

Article last edited on: 2012-05-21 11:39:16

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential