How to fix "defined in discarded section" linker error?
c++, g++, linker-errors
Solution
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.
Problem
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?