2016-02-12 48 views
0

我正在編寫一個使用execv()編譯並運行另一個程序的程序。我寫了一個名爲helloWorld.c的簡單C程序,它在執行時輸出「Hello world」,另一個名爲testExec.c的文件應該編譯並運行helloWorld.c。我一直在四處尋找找到一種方法來做到這一點,但我還沒有找到任何答案。 testExec.c中的代碼是:使用exec編譯並運行c程序()

#include <stdio.h> 
#include <unistd.h> 
int main(){ 
    char *args[] = {"./hellWorld.c", "./a.out", NULL}; 
    execv("usr/bin/cc", args); 
    return 0; 
} 

testExec.c編譯時沒有錯誤。但是,當我運行它時,出現一個錯誤消息:「致命錯誤:-fuse-linker-plugin,但找不到liblto_plugin.so。編譯終止。」我認爲這意味着helloWorld.c正在被編譯,但是當它運行helloWorld.c時會拋出這個錯誤。我想也許是因爲我有a.out和helloWorld.c以'./'開頭。我從兩者中刪除了'./',然後單獨一個,仍然沒有運氣。

我還做了'sudo apt-get install build-essential'以及'sudo apt-get install gcc'。我不確定這是否能解決問題,但我真的不知道還有什麼可以嘗試的。無論如何,任何幫助將不勝感激!

+0

'CC --help'說,輸出文件名必須是通過'-o'選項指定,但你似乎沒有'-o'傳遞它。這可能意味着它被視爲輸入。 –

回答

0

您在致電cc時錯過了前導斜槓。

另外,參數列表中的第一個參數是可執行文件的名稱。之後的實際論據。您也不使用-o來指定輸出文件的名稱。

#include <stdio.h> 
#include <unistd.h> 
int main(){ 
    char *args[] = {"cc", "-o", "./a.out", "./hellWorld.c", NULL}; 
    execv("/usr/bin/cc", args); 
    return 0; 
} 

編輯:

上面只編譯。如果你想編譯和運行,你可以這樣做:

#include <stdio.h> 
#include <unistd.h> 
int main(){ 
    system("cc -o ./a.out ./hellWorld.c"); 
    execl("./a.out", "a.out", NULL); 
    return 0; 
} 

雖然這可能是最好的,因爲一個shell腳本來完成:

#!/bin/sh 

cc -o ./a.out ./hellWorld.c 
./a.out 
+0

好的,太好了。錯誤不再被拋出,但我想我可能錯誤地解釋了helloWorld.c的函數。 helloWorld.c調用printf(「hello world \ n」);向終端打印「hello world」。在我進行了你建議的更改後,文件testExec.c編譯並運行時沒有錯誤,但終端中沒有顯示「hello world」。 – Hossam

+0

@Hossam看我的編輯。 – dbush

+0

謝謝!它非常完美! – Hossam