For a hello world program, hello.c
, does it matter if I compile it to a file name ending in .o
? Or is it just a convention? E.g. should I do this:
gcc -o hello.o hello.c
Or this:
gcc -o hello hello.c
In a Linux environment
CodePudding user response:
By convention extension (in linux at least) .o
implies an Object File, not an executable. So, yes, you can use this extension, as in gcc -o hello.o hello.c
, but it's misleading and a bad idea. Better to do gcc -o hello hello.c
.
However, if you are building the object file (i.e. compile only, not link) you would use the -c
option, as in gcc -c hello.c
, which will create the object file hello.o
.
(Just summarizing what's already in the comments.)
CodePudding user response:
By convention extension (in linux at least) .o implies an Object File, not an executable. So, yes, you can use this extension, as in gcc -o hello.o hello.c, but it's misleading and a bad idea. Better to do gcc -o hello hello.c.
CodePudding user response:
The situation here is a bit confusing because there are two kinds of "object files" — those that are truly intermediate object files (the ones normally ending in .o
), and final executables.
You can use a typical command-line C compiler in two ways. You can compile to an intermediate object file, using the -c
option, and then "link" to a final executable as a second step:
cc -c -o hello.o hello.c # step 1
cc -o hello hello.o # step 2
Or you can compile and link in one fell swoop:
cc -o hello hello.c # step 3
In the first case, when you compile and link in separate steps, the extension .o
for the intermediate object file is more or less mandatory, because in the "link" step ("step 2"), that's how the compiler actually knows it's looking at an intermediate object file. Notice the difference between steps 2 and 3. In step 3, the way the compiler knows it has some compiling to do is the extension .c
. In step 2, on the other hand, the extension .o
tells it the file is already compiled, and merely needs to be linked.
Also, as you may know, the extension .o
is very much the default when compiling only. In step 1, it would have sufficed to just say cc -c hello.c
.
The advantage to "separate compilation" is that it gives you a lot more flexibility. If you have a larger program, made from several source files, you could recompile everything, all at once, every time, like this:
cc -o program file1.c file2.c file3.c
But if you compile separately, like this:
cc -c file1.c
cc -c file2.c
cc -c file3.c
cc -o program file1.o file2.o file3.o
then later, when you make a change to, say, file2.c
, you can take a shortcut and only recompile that one file. (This does come at the cost of some disk space, to keep all those intermediate .o
files around, and some complexity and extra typing, which for larger programs you usually let a build program like make
take care of for you.)