Clang LTO does not work for static library on Linux
This is caused by wrong ar
and ranlib
executable used.
to reproduce:
CMakeLists.txt:
project(cmake-clang-lto CXX)
add_compile_options(-flto)
add_link_options(-flto)
add_library(lib STATIC lib.cpp)
add_executable(main main.cpp)
target_link_libraries(main lib)
main.cpp
#include "lib.h"
int main() {
hello();
}
lib.h
#pragma once
void hello();
lib.cpp
#include "lib.h"
#include <iostream>
void hello() {
std::cout << "Hello" << std::endl;
}
Run with:
mkdir build
cd build
CXX=clang++ cmake ..
make
Produce Error:
[100%] Linking CXX executable main
/usr/bin/ld: liblib.a: error adding symbols: archive has no index; run ranlib to add one
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Add the following lines after project(...)
in CMakeLists.txt workarounds this problem
SET(CMAKE_AR ${CMAKE_CXX_COMPILER_AR} CACHE PATH "AR" FORCE)
SET(CMAKE_RANLIB ${CMAKE_CXX_COMPILER_RANLIB} CACHE PATH "RANLIB" FORCE)
This will tell CMake to use /usr/lib/llvm-10/bin/llvm-ar
and /usr/lib/llvm-10/bin/llvm-ranlib
. But since CMake has already detected these executables, why not use them by default?
OS: Ubuntu 20.04 CMake: 3.17.3 Clang: 10.0.0-4ubuntu1
I've also tested this on Ubuntu 18.04 on GitHub Actions. Still the same error.