主要原因是建立速度,正如其他人已经正确指出的那样。例如,使用静态库编译(默认情况下)比使用仅头文件编译快约2.75倍:
#include <fmt/core.h>
int main() {
fmt::print("The answer is {}.", 42);
}
% time c++ -c test.cc -I include -std=c++11
c++ -c test.cc -I include -std=c++11 0.27s user 0.05s system 97% cpu 0.324 total
% time c++ -c test.cc -I include -std=c++11 -DFMT_HEADER_ONLY
c++ -c test.cc -I include -std=c++11 -DFMT_HEADER_ONLY 0.81s user 0.07s system 98% cpu 0.891 total
在仅由头文件构成的库中,实现细节和依赖关系会泄露到使用它们的每个翻译单元中。
像 vformat
这样的函数不是模板。将它们放在头文件中并减慢整个编译过程毫无意义。我想这就是背后的原理。 fmt
库似乎非常关心编译时间。