undefined reference cross compiling static libraries with LTO under GCC
Asked Answered
P

1

11

I am attempting to use GCC 4.9.2 to cross compile an application from Linux (x86_64-pc-linux-gnu) for Windows (x86_64-w64-mingw32).

When building targets that link against static libraries and also using link-time optimisation I get undefined reference errors from the linker for all symbols the target uses from the library.

eg, building bar.a from bar.cpp

int bar (void) {return 42;}

and linking with foo.cpp

extern int bar (void);
int main (int, char**) {bar ();}

using the command line

x86_64-w64-mingw32-g++ -flto -o foo.o -c foo.cpp
x86_64-w64-mingw32-g++ -flto -o bar.o -c bar.cpp
x86_64-w64-mingw32-gcc-ar rc bar.a bar.o
x86_64-w64-mingw32-gcc-ranlib bar.a
x86_64-w64-mingw32-g++ -flto -fuse-linker-plugin foo.o bar.a -o foo

Results in the error

/tmp/ccc3Twsc.lto.o:foo.o:(.text+0x15): undefined reference to `bar()'
collect2: error: ld returned 1 exit status

From above:

  • I am using the gcc-wrappers for ar/ranlib
  • there are no external dependencies
  • all files are compiled with the same options

I have tried using various combinations of -fuse-linker-plugin, gcc-ar vs ar, symbol visibility options, optimsations, etc but I can't get it to link correctly without turning off LTO.

All targets build correctly under the native compiler (x86_64 Linux).

Is there something obvious I'm missing here?

Pane answered 9/12, 2014 at 6:24 Comment(0)
D
2

I'm able to reproduce this linking problem on Mingw32-gcc 4.9.2 under Win7 64-bit. However, I did get it to link successfully by adding -ffat-lto-objects as a workaround:

g++ -flto -o foo.o -c foo.cpp
g++ -flto -ffat-lto-objects -o bar.o -c bar.cpp
ar rc bar.a bar.o
g++ -flto -o foo.exe foo.o bar.a
Dysplasia answered 9/12, 2014 at 7:41 Comment(2)
Thanks for the confirmation. Unfortunately -ffat-lto-objects allows the linker to fall back to the standard method of linking and more or less negates LTO for my purposes (using lots of convenience libraries).Pane
Also, note that gcc-ar (as opposed to ar) will likely be a requirement to confirm as ar does not understand the LTO/GIMPLE object sections. gcc-{ar,ranlib,nm} are temporary wrappers that preserve/understand the relevant sections.Pane

© 2022 - 2024 — McMap. All rights reserved.