__attribute((used))has been declared, but the variable is still deleted when linking

test code:

int TestMain()
return 0;

#pragma clang section rodata=".rti_fn.6"
__attribute((used)) const init_fn_t __rt_init_TestMain = TestMain;
#pragma clang section rodata=""

If you link to a .o file, no problem. But if you use armar to generate the.a file and then link it, the variable is deleted

How to solve this problem?

  • Hi,

    Please, refer to https://developer.arm.com/docs/100070/latest/linker-command-line-options/input-file-list 

    The attribute `used` affects the process of removing unused sections from an image. In order for a variable to be considered at all, it first need to be included in the image.

    As the note in the above documentation link says, members from the libraries are added to the image only when they resolve an unresolved non weak reference. The presence of `__attribute__((used))` variables is not a reason by itself to include an object file in the output image, it prevents a variable from being discarded, but does not force a variable to be included.

    The desired affect can be achieved by the alternative form of specifying libraries on the linker command line, for example:
    armlink -o output.elf file0.o file1.o ... "test.lib(*.o)"

    That will include all object files in the output image, even if they do nor resolve anything. Then the symbols, declared with `__attribute__((used))` will not be discarded.

    Hope this helps.

    Best regards, 


More questions in this forum