arrowd
arrowd

Reputation: 34401

Does passing multiple files to C/C++ compiler allows for interprocedural optimization?

Let's say I have foo.cpp with following content

int foo() {
  return 123;
}

and main.cpp in which I use foo:

int main() {
  int r = foo();
  return r;
}

I can compile both source files into object code and then link them using link-time optimizations to make foo() call inlined into main().

But can I achieve the same effect by listing both files in compiler command line, like c++ foo.cpp main.cpp? Or is it just boils down to

foreach(file in files)
  UsualCompilingRoutinesForSingleFile(file)

?

If yes, why compiler isn't allowed to concatenate all files passed in into a single one to achieve sort of LTO?

Upvotes: 2

Views: 906

Answers (2)

Klaus
Klaus

Reputation: 25613

If yes, why compiler isn't allowed to concatenate all files passed in into a single one to achieve sort of LTO?

The compiler is allowed and able to "see" all files at the "same time" to perform LTO. But that is indeed not the same as having a single source file.

From the gcc docs ( only as an example, other compilers support similar technology ):

LTO mode, in which the whole program is read into the compiler at link-time and optimized in a similar way as if it were a single source-level compilation unit.

As you can see, the result will be the same as it would be if you present all files at once to the compiler, but without having trouble from ordering all the included headers / sources in the "correct" order.

For more information from gcc for link time related optimization levels & methods: https://gcc.gnu.org/onlinedocs/gccint/LTO-Overview.html

Upvotes: 2

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

Concatenating the files is not the same, due to local/static objects. You can have conflicts (think unnamed namespaces). For instance the first file uses a local function foo that looks up in a static map something, and then the second file has another local function foo that looks up in a hash map (for whatever reason, and yes I agree that it's also a bad design).

If you compile both files together, concatenating them, then you break encapsulation from translation units and you get multiple definitions of the same files.

In your example, the compiler compiles both files separated and the links the together, it's not LTO, which is something else (not generating just object files, but also a kind of AST that can be merged with others, and then optimized).

Upvotes: 2

Related Questions