views:

205

answers:

4

When we are compiling a C program the output is stored in a.out. How can we redirect the compiled output to another file?

+5  A: 

-ofilename will make filename instead of a.out.

Daniel A. White
+1  A: 

According to the manual:

-o <file>  Place the output into <file>
Arkaitz Jimenez
+4  A: 

Most C compilers provide the -o option for this, such as:

gcc -o gentext gentext.c
cc  -o mainprog -Llib -lmymath firstbit.c secondbit.o
xlc -o coredump coredump.c
paxdiablo
+1  A: 

In Unix, where C originated from, C programs are usually compiled module-by-module, and then the compiled modules are linked into an executable. For a project that consists of modules foo.c and bar.c, the commands would be like this:

cc -c foo.c
cc -c bar.c
cc -o myprog foo.o bar.o

(With -c, the output filename becomes the source file with the suffix replaced with .o.)

This allows you to also re-compile only those modules that have changed, which can be a big time saver for big programs, but can also become pretty tricky. (This part is usually automated using make.)

For a single-module program there's not really any point in first compiling to a .o file, and then linking, so a single command suffices:

cc -o foo foo.c

For single-module programs, it is customary to call the resulting executable program the same as the C source file without the .c suffix. For multi-module programs, there is no hard custom on whether the output is named after the file with the main function or not, so you're free to invent whatever strikes your fancy.

Lars Wirzenius