将所有C代码写入单个源文件是否会使程序运行得更快?

Jus*_*ner 3 c performance compilation

我刚刚注意到在sqlite 3源代码文件的开头,它说:

/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.27.1.  By combining all the individual C code files into this
** single large file, the entire code can be compiled as a single translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% or more are commonly seen when SQLite is compiled as a single
** translation unit.
Run Code Online (Sandbox Code Playgroud)

我以前不知道这个,也找不到支持它的权威来源.这是真的?那么C++呢?

klu*_*utt 5

它不会自动使它更快,但它有一些道理.将所有内容都放在一个文件中允许编译器进行其他情况下无法实现的优化.例如,函数不能内联,除非它属于调用它的同一个转换单元.

内联函数基本上意味着函数调用被函数体替换.这样做的好处是你可以跳过跳转到功能代码和返回跳转.但是如果函数在另一个转换单元中,那么编译器将只知道函数的原型而不是函数体,这反过来意味着它必须跳转.

话虽如此,我强烈建议不要使用这种方法.如果您确实需要最终调整,那么使用某种可以从源树创建单个c文件的脚本.

  • 今天,许多编译器/链接器提供链接时间优化.这应该给你相同的好处. (3认同)