Why do we need object files? I've tried linking multiple files by using the command g++ -o main.exe main.cpp (other files).cpp
, and it works. However, from tutorials online, it needs the files to be turned into *.o files first by using the command g++ -c main.cpp (other files).cpp
, and use g++ -o main.exe main.o (other files).o
to link the files together. If we can just do the same thing with g++ -o main.exe main.cpp (other files).cpp
, why do we need to turn files into *.o first?

- 13
- 2
-
Does this answer your question? [What is \*.o file?](https://stackoverflow.com/questions/2186246/what-is-o-file) – justANewb stands with Ukraine Oct 27 '21 at 06:56
-
Let's say you have a 3-million-line c++ project. You change one line of code. Do you want to recompile the whole thing every time you do that? Or would you like to have a mechanism where you can just recompile the one file you changed and reuse the rest? Yes, for small projects you might not see the point. Think big. – Oct 27 '21 at 07:03
-
Also C++ compilation is usually memory intensive. You would not actually be able to compile millions of lines in one go anyway. – Oct 27 '21 at 07:04
-
@dratenik Do you mean the *.o files will allow you to recompile one of the files instead of all of them? Or is it the opposite? Because now I just run the command again and again after every changes. – LiDL Oct 27 '21 at 07:36
-
Libraries are generally just collections of object files in some form (with extensions like `.lib`, `.a`, `.so`, `.dll`) and the corresponding API (header files). – Daniel Langr Oct 27 '21 at 07:39
-
The usual way to construct projects is to have a Makefile which describes what is made from what and allows you to recompile files whose ingredients have changed since last time. – Oct 27 '21 at 07:51
-
I see! Thanks a lot! – LiDL Oct 27 '21 at 08:04
1 Answers
TL;DR version:
You don’t need to create the object files. It’s fine to directly compile into an executable.
Long version:
You do not need to explicitly create the object files here. However, do note that the compiler does create these object files as intermediate files for each source file. Once, the compiler has all the object files available, the linker comes into play and matches definitions of each function with an implementation (amongst other things). The linker finally creates the executable and deletes the object files since you didn’t ask for them.
However, you can ask the compiler to store these intermediate files using the command as stated in your question.
As mentioned in the comments, it’s almost always good practice to compile only the source files that have changed in the last development cycle. This necessitates that you have object files available for the unchanged source files. I simply wanted to state that directly compiling is legal.

- 32,622
- 4
- 31
- 60

- 81
- 5