简体   繁体   中英

Is there a difference in a binary when using multiple files C as opposed to putting it all into a single file?

I know that multiple files will by far make code easier. However do they offer a performance difference between "jamming it all into one file" or will a modern compiler like gcc create the same binaries for both. When I say performance difference I mean file size, compile time, and running time.

This is for C only.

Arguably, compile times improve with multiple files, as you only need to recompile files that have changed (assuming you have a decent dependency-tracking build system).

Linking would probably take longer, as there's just more to do.

Traditionally, compilers have been unable to perform optimizations across multiple source files (things like inlining functions is tricky). So the resulting executable is likely to be different, and potentially slower.

There are more opportunities for optimization when everything is in a single file. Eg gcc, starting with -O2 , will inline some functions if their body is available, even if they aren't declared inline (even more functions are eligible for inlining with -O3 ). So there are differences in run time, and sometimes you even have a chance to notice them. Even more so with -fwhole-program , telling GCC that you don't care about out-of-line versions of external functions except main() (GCC behaves as if all your external functions became static).

Overall compile time may increase (because there is more stuff to analyze, and not all optimizer algorithms are linear) or decrease (when there's no need to parse the same headers multiple times). Binary size may increase (due to inlining, in exchange for running faster) or decrease (less likely; but sometimes, inlining simplifies caller's code to the point where code size decreases).

As of the ease of development and maintenance, you can use sqlite's approach: it has multiple source files, but they are jammed into one ("amalgamation") before compilation.

From some tests, compiling and linking take longer. You will receive a different binary, at least I did, however mine was within a byte of the other.

The all-in-one file ran in .000764 MS The Multiple files version ran in .000769 MS Do take the benchmark with a grain of salt, as I did put it together in about 5 minutes, and it was a tiny program.

So really no differences overall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM