2015-10-19 129 views
0

我需要用系統編譯一個程序,我有存檔的名字和執行文件的名字,子執行gcc -o file.c exe1,父執行./exe1例如用C編譯系統

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <string.h>  

int main(int argc,char *argv[]) 
{ 
    if (argc != 3) { 
     printf("Debe ingresar el nombre del archivo a compilar y el ejecutable"); 
     exit(1); 
    } else { 
     char *archivo1 = strcat("gcc ", argv[1]); 
     char *archivo2 = strcat(archivo1, ".c -o "); 
     char *archivo3 = strcat(archivo2, argv[2]); 
     char *ejecutable = strcat("./", argv[2]);  
     pid_t pid_hijo; 
      int valor; 
     switch(pid_hijo = fork()) { 
      case -1: 
       printf("No se pudo crear el hijo"); 
      case 0: 
       valor = system(archivo3); 
      default: 
       wait(NULL); 
       valor = system(ejecutable); 
     } 
    }   
    return 0; 
} 
+1

你'case'塊應該有'breaks'。 –

+1

看看sprintf()而不是strcat – Jack

回答

2

char *archivo1=strcat("gcc ",argv[1]); 

是不確定的行爲。

"gcc "是一個字符串,它只是讀過,strcat()將嘗試寫它,實際上超出"gcc "末,試圖寫入超出數組的結尾也是不確定的行爲,但在這種情況下,它不是數組,因此從任何角度來看都是非法的。

你需要snprintf()代替,這樣

char command[200]; 
ssize_t result; 
result = snprintf(command, sizeof(command), "gcc %s -o %s", argv[1], argv[2]) ; 
if (result >= (ssize_t) sizeof(command)) 
    error_cannot_store_the_command_in_command(): 
+1

不錯,不知道在答案中寫標籤的可能性...... – Downvoter

+1

@cad是的,你可以'[tag:c]'。 –

+0

找不到我/:這會返回一個分段錯誤 –