Search code examples
cunixexecutablecc

UNIX cc executable location


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


Solution

  • 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