3

I'm trying to create static library with link time optimization using cmake and g++.

set(
    CMAKE_CXX_FLAGS
        "${CMAKE_CXX_FLAGS} -Wall -Werror -Wextra -pedantic -std=c++11"
)

if (CMAKE_COMPILER_IS_GNUCXX)
    set(
        CMAKE_STATIC_LINKER_FLAGS_RELEASE
            "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} -flto -fwhole-program"
    )
endif()

add_library(
    mylib STATIC
        mylib.cpp
)

But when running typical

cmake -DCMAKE_BUILD_TYPE=Release ..
make

I'm getting following error:

/usr/bin/ar: two different operation options specified

link.txt file contains following commands:

/usr/bin/ar cq libmylib.a  -flto -fwhole-program CMakeFiles/mylib.cpp.o
/usr/bin/ranlib libmylib.a

From what I understand from running ar --help the -flto -fwhole-program should be before libmylib.a in the first line. But I have no idea how to force CMake to put it there.

Is my assumption correct? And how can I resolve this?

EDIT: I'd like to add that I'm completely new to using LTO so if it doesn't make sense to use it for static libraries, please do tell me so.

graywolf
  • 7,092
  • 7
  • 53
  • 77
  • [GCC documentation states](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html): "-fwhole-program ... This option should not be used in combination with -flto." – m.s. Jul 24 '15 at 22:36
  • another part says "If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities.". Does static library need to export any symbols? sorry for probably stupid question – graywolf Jul 24 '15 at 22:41
  • I can't help with the library optimization part, but if you just want to change the `ar` command line see [CMAKE_CXX_ARCHIVE_CREATE](https://github.com/Kitware/CMake/blob/master/Modules/CMakeCXXInformation.cmake#L268). So you could add `set(CMAKE_CXX_ARCHIVE_APPEND " cq -flto -fwhole-program ")` before your `project()` command or - better - in a toolchain file for GNU (`CMAKE_COMPILER_IS_GNUCXX` is not valid before `project()`). See [here](http://stackoverflow.com/questions/30503631/cmake-in-which-order-are-files-parsed-cache-toolchain) for details. – Florian Jul 27 '15 at 08:12
  • my CMakeLists is for src subfolder, `project()` is defined in the root CMakeLists.. thank you very much for your advice, can you post it as an answer? I will try it when I get home from work and accept it if working. And thank you for mentioning `toolchain file`, will read more on that topic – graywolf Jul 27 '15 at 12:42

1 Answers1

4

-flto isn't a valid option for ar. You should instead use these flags for CMAKE_EXE_LINKER_FLAGS.

bb94
  • 1,294
  • 1
  • 11
  • 24