如何将lto与静态库一起使用?

时间:2014-09-16 21:05:16

标签: c++ gcc lto

当我尝试使用-flto构建静态库时,我得到未定义的引用错误:

library.cpp

#include <iostream>

void foo() {
  std::cout << "Test!" << std::endl;
}

的main.cpp

void foo();

int main() {
  foo();
  return 0;
}

编译输出

$ g++ -flto -c library.cpp
$ ar rcs library.a library.o
$ g++ -flto main.cpp library.a
/tmp/ccZIgxCY.ltrans0.ltrans.o: In function `main':
ccZIgxCY.ltrans0.o:(.text+0x5): undefined reference to `foo()'
collect2: error: ld returned 1 exit status

如果我与library.o而不是library.a相关联,则可以正常使用。我错过了什么?这是GCC 4.9.1和binutils 2.24。

2 个答案:

答案 0 :(得分:22)

正如我在GCC开发人员HonzaHubička发表的this帖子中发现的那样,答案是单独使用gcc-ar包装而不是ar

$ gcc-ar rcs library.a library.o

这会使用正确的插件参数调用ar,在我的情况下是

--plugin /usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.1/liblto_plugin.so

答案 1 :(得分:2)

作为一个补充答案:在GCC中,还可以使用const arrayA = ['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'] const arrayB = ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'] let results = [{a: arrayA, b: arrayB}] for (let i = 0; i < arrayA.length; i++) { let newResults = [] for (let j = 0; j < results.length; j++) { let result = results[j] // Copy the arrays let outA = result.a.slice() let outB = result.b.slice() // Get the items to switch let itemA = outA[i] let itemB = outB[i] // Switch positions in the new arrays outA[i] = itemB outB[i] = itemA // Append the new item to the results newResults.push({a: outA, b: outB}) } results = results.concat(newResults) } console.log(results.length) ,它将经典的目标代码添加到存档中的文件中。这样就可以在不带-flto的代码中使用静态库。