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?
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