After compiling a (C/C++) code with GNU Make (or SCons) and successfully creating a binary, is there any reason to keep the .o
object files?
Can I always safely remove them or are there cases where they are referenced by the binary?
Once you have created your executable by linking the object files (and the libraries on which they depend) the object files are waste material as far your executable is concerned. You can safely delete them.
However, if you build your executable with a build system such as GNU Make or Scons it is certainly inadvisable to make that build system delete the object files of a successful build.
The main purpose of such a build system is to rebuild your executable,
when it needs rebuilt, with the smallest amount of rebuilding that is
necessary. If the executable prog
requires object files a.o
, b.o
and c.o
to
be linked and you change only the source file c.c
, then the build system
will know that it can rebuild prog
merely by recompiling c.c
and then relinking prog
with the new c.o
plus the old a.o
and b.o
.
But it can only deliver this economy if the old a.o
and b.o
still exist.
If you've deleted them with your last successful build then prog
must
be rebuilt from scratch, although the new a.o
and b.o
will be the same
as the old ones: a waste of time.
There will of course be occasions when you want to rebuild from scratch, and
to do so you must first delete all the object files. To support that
need in GNU Make you provide your project with a phony target,
conventionally called clean
, that does nothing but delete the object files
and any other intermediate by-products of the build. You invoke it explictly with:
make clean
In Scons, you don't need to write anything extra in your build project to
clean out intermediate prodpucts. You just run scons -c
or scons --clean
.
But in either case, you do not want to delete the object files of a successful
build by default, as that defeats the purpose of the build system.