Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "defined in discarded section" linker error?

My program compiles fine without -flto but with -flto I get this error:

% arm-none-eabi-g++ --version
arm-none-eabi-g++ (4.8.3-9+11) 4.8.3 20140820 (release)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

% arm-none-eabi-g++ -O2 -W -Wall -fPIE -flto -march=armv7-a -mfloat-abi=hard -mfpu=vfpv3-d16 -ffreestanding -nostdlib -std=gnu++11 -fno-exceptions -fno-rtti -c -o main.o main.cc

% arm-none-eabi-g++ -fPIE -nostdlib -O2 -flto boot.o memcpy.o font.o main.o -lgcc -Tlink-arm-eabi.ld -o kernel.elf
`memcpy' referenced in section `.text' of /tmp/ccYO5wE8.ltrans0.ltrans.o: defined in discarded section `.text' of memcpy.o (symbol from plugin)
collect2: error: ld returned 1 exit status

I tried moving the memcpy.o to different positions to try different link orders but the error is always the same. I've seen that this is a common problem but none of the answeres to previous questions applies. I don't have a broken boost installed or using different compiler versions to compile. I'm building a bare-metal kernel so there isn't any outside library involed other than libgcc.

Anyone an idea what is going on there?

like image 310
Goswin von Brederlow Avatar asked Feb 24 '15 23:02

Goswin von Brederlow


People also ask

How do you fix a linker error?

You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass . obj files or . lib files that contain the definitions to the linker.

What causes linker error?

Linker errors occur when the linker is trying to put all the pieces of a program together to create an executable, and one or more pieces are missing. Typically, this can happen when an object file or libraries can't be found by the linker. Fixing linker errors can be tricky.


1 Answers

This seems to be a compiler bug that was fixed in gcc-4.7 and reapeared in gcc-4.8 (gcc bugreport for 4.6, reapearance in 4.8). A quick workaround is to mark the function used:

void * memcpy(void *dest, const void *src, sizte_t n) __attribute__((used));
void * memcpy(void *dest, const void *src, size_t n) {
    uint8_t *d = (uint8_t *)dest;
    uint8_t *s = (uint8_t *)src;
    while(n--) {
    *d++ = *s++;
    }
    return dest;
}

That stops the optimizer from discarding the function. Thanks to Richard Biener for suggesting that.

like image 167
Goswin von Brederlow Avatar answered Sep 28 '22 08:09

Goswin von Brederlow