2010-09-01 89 views
3

當我使用cc命令編譯.c文件時,它會創建一個a.out可執行文件。我注意到它在我的當前目錄中創建a.out文件。有沒有辦法使a.out文件與我碰巧在系統中的.c文件在同一個目錄下創建?UNIX cc可執行文件位置

例如如果我當前的路徑是~/desktop,我在鍵入命令:

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

它創建a.out文件中~/desktop目錄。我想創建a.out文件path/to/my/file/a.out

+1

除了那些已經被張貼的答案(而哪些有幫助),我建議學習如何編寫一個'Makefile'(如果你的項目可能會變得更大,可能會使用autoconf/automake)。 – Bruno 2010-09-01 12:44:18

回答

5

你將不得不使用-o每次調用CC時間切換:

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

,或者你可以做一個包裝腳本是這樣的:

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 

那麼你可以調用

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

,它會反過來,調用

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

當然,你可以把mycc在$ PATH的,所以你可以這樣調用它:

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

這可能是一個別名嗎? – fuz 2010-09-01 12:10:36

+0

您也可以命名輸出文件,如.c文件,即'test.c' - >'test.out',如下所示:'cc $ 1 -o $(dirname $ 1)/ $(basename $ 1 .c)。out「' – adf88 2010-09-01 12:21:57

+0

@FUZxxl你不能簡單的別名cc來做到這一點,cuz不幸的是,你不能傳遞參數給別名(因爲我剛剛發現:)) – aularon 2010-09-01 12:35:16

1

是的,用-o

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

您可以給「-o」標誌來定義輸出文件。例如:

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

它可能不是你要找什麼,但你可以很容易地使用-o siwtch這樣重定向編譯輸出:

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

我不知道如何archieve,你想要什麼(自動更換),但我想你可以用一些像這樣的慶典做:(我在腳本較差,未經測試,可能是錯誤的):

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

這應該C將i中指定的文件複製到同一目錄中的輸出文件中,但刪除了.c後綴。

+0

您需要提供文件路徑而不是目錄。你的'-o'選項有一個缺失的文件名。 – codaddict 2010-09-01 12:06:38

+0

儘管我很傷心,但我在shell腳本中很糟糕。不應該像'$ i ='a/b/file.c' - >'cc -o a/b/file a/b/file.c'這樣做嗎? – fuz 2010-09-01 12:09:26