views:

74

answers:

4

When I compile a .c file using the cc command, it creates an a.out executable. I've noticed that it creates the a.out file inside my current directory. Is there a way to make the a.out file be created in the same directory as the .c file wherever I happen to be on the system?

for example if my current path is ~/desktop and I type in the command:

cc path/to/my/file/example.c

It creates the a.out file in the ~/desktop directory. I would like it to create the a.out file in path/to/my/file/a.out

+1  A: 

Yes, with -o.

cc path/to/my/file/example.c -o path/to/my/file/a.out
Richard Fearn
+2  A: 

You can give the "-o" flag to define the output file. For example:

cc path/to/my/file/example.c -o path/to/my/file/a.out
pma
+1  A: 

It may be not what you're looking for, but you can easily redirect the output of a compilation using the -o siwtch like this:

cc -o /a/dir/output b/dir/input.c

I don't know, how to archieve, what you want (auto replacement), but I guess you can do it with some bash like this: (I'm poor in scripting, untested and may be wrong):

i = "a/path/to/a/file.c" cc -o ${i%.c} $i

This should compile a file specified in i into an output file in same dir, but with the .c-suffix removed.

FUZxxl
you need to provide path to a file not a directory. Your `-o` option has a missing filename.
codaddict
As I sad, I'm bad at shell scripting. Shouldn't do this something like `$i = `a/b/file.c` -> `cc -o a/b/file a/b/file.c`?
FUZxxl
+4  A: 

You will have to use the -o switch each time you call cc:

cc -o path/to/my/file/a.out path/to/my/file/example.c

or you can make a wrapper script like this:

mycc

#!/bin/bash

dirname=`dirname "$1"`
#enquoted both input and output filenames to make it work with files that include spaces in their names.
cmd="cc -o \"$dirname/a.out\" \"$1\""

eval $cmd

then you can invoke

./mycc path/to/my/file/example.c

and it will, in turn, call

cc -o "path/to/my/file/a.out" path/to/my/file/example.c

of course you can put mycc in $PATH so you can call it like:

mycc path/to/my/file/example.c
aularon
Is this possible as an alias?
FUZxxl
You can also name output file like .c file i.e. `test.c` -> `test.out`, something like this: `cc $1 -o $(dirname $1)/$(basename $1 .c).out"`
adf88
@FUZxxl you can not simple alias cc to do this, cuz unfortunately you can't pass parameters to aliases (as I just found out :) ).
aularon
Okay (As I sad, I've no experiences in shell scripting).
FUZxxl
this works great for what I need. is there a way to also make it accept files whose path has a space in it? ultimately, I would like to type mycc and drag the file into terminal and not worry if one of the folders in the file path has a space in it.
Ohnegott
I edited the script above to enquote the input filename as well as the output filename. It shoould work now for filenames containing spaces.
aularon