Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need compiling and linking separately?

Tags:

c++

c

Is that possible to link at the time of compiling, and remove the separate linking step?

like image 685
Round Robin Avatar asked Oct 07 '13 12:10

Round Robin


2 Answers

You compile one or more translation units at a time, but as far as the language is concerned each TU is considered in isolation when compiling. You link one or more translation units together.

So, if all the TUs in the program are compiled at the same time, you can link them at that time (well, normally the linking would be immediately after the compilation, but that's an internal detail and there's nothing to stop you from writing a compiler/linker that somehow interleaves the steps so that there's no single point that occurs after all compilation has finished but before any linking starts).

However, if you only compile one TU out of many that will later be linked together to make a program, then of course you cannot link at the same time. Link with what? The other TUs might not even have been written yet, especially if the TU you are compiling is for distribution as a staticly-linked library.

like image 172
Steve Jessop Avatar answered Nov 03 '22 02:11

Steve Jessop


Short answer: yes, it's entirely possible. In fact, it's actually been done.

Some old Pascal compilers (e.g., early versions of Turbo Pascal) didn't have a separate linker. To create your executable, you compiled all the code together. Rather than track which standard library functions were used, and linking in only those that were needed, they simply copied the entire standard library (all ~8 kilobytes of it) into the executable.

To make this practical, you clearly need a fast compiler, small projects, or (probably) both.

When you were working on a system with 64 kilobytes of RAM and mass storage was a floppy disk drive that held around 100 to 200 kiloybtes or so, you weren't left with a lot of choice about that. Nowadays, I can't quite imagine anybody putting up with the same (or even similar) limitations.

All that said, it's not a model that fits very well with C or C++. They were designed from the beginning with the assumption of separate compilation and linking. Quite a few parts of the language proper (e.g., file-level static variables) only really work when you at least imitate separate linking.

like image 40
Jerry Coffin Avatar answered Nov 03 '22 01:11

Jerry Coffin