编译器如何使用预编译库?

How do compilers used precompiled libraries?

我不明白编译器在使用预编译库时如何知道要做什么。例如,假设我的程序是

#include <vector>
#include <iostream> 

int main() 
{
   std::vector<int> V = {1, 69, 111}; 
   for (std::vector<int>::iterator it(V.begin()), offend(V.end()); it != offend; ++it) 
         std::cout << *it << std::endl;
   return 0;
}

显然 std::vector 对于这个简单的程序来说有点过分了。但是编译器怎么知道,除非它知道std::vector在C++语言中是如何实现的?

您的示例中可能没有 "precompiled binaries"。但是,您使用的是 standard C++ library (which provides the operations on cout and headers like <vector>); read more about software libraries(事实上,Linux 上的 libstdc++.so 共享库是编译后的二进制形式)。

你有一个 #include <vector> 然后你正在使用 std::vector<int> 实例化一个 C++ template 所以编译器定义了一些 类 和函数(std::vector<int> 需要) 并发出相关代码。

阅读更多关于 compilers and linkers, e.g. Levine's book on Linkers & loaders; the documentation of GCC also has a chapter on template instantiation

顺便说一句,您可能会查看程序的 preprocessed 形式(假设在文件 yoursource.cc 中)。如果使用 GCC 使用
g++ -Wall -C -E yoursource.cc > yoursource.ii 编译该源代码,然后使用编辑器或寻呼机查看(相当大的)yoursource.ii 生成的文件,这与编译器的实际情况非常相似 "seeing"

我猜你想的是 precompiled headers。库由一组 object 文件组成,这些文件先前已编译或组装。如前所述,模板是一种源代码形式,包含在 headers.