編譯C程式碼時出錯

編譯C程式碼時出錯

我找到了一段 C 程式碼,這對於我想要在此連結下執行的操作非常有用:所有可能的字元和數字組合

#include <stdio.h>

//global variables and magic numbers are the basis of good programming
const char* charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char buffer[50];

void permute(int level) {
  const char* charset_ptr = charset;
  if(level == -1){
    puts(buffer);
  }else {
   while(buffer[level]=*charset_ptr++) {
    permute(level - 1);
   }
  }
}

int main(int argc, char **argv)
{

  int length;
  sscanf(argv[1], "%d", &length); 

  //Must provide length (integer < sizeof(buffer)==50) as first arg;
  //It will crash and burn otherwise  

  buffer[length]='\0';
  permute(length - 1);
  return 0;
}

但是,當我嘗試按照建議編譯它時,出現以下錯誤。有人可以幫我改正嗎?

$ make CFLAGS=-O3 permute && time ./permute 5 >/dev/null
make: Nothing to be done for 'permute'.
./permute: line 3: //global: No such file or directory
./permute: line 4: const: command not found
./permute: line 5: char: command not found
./permute: line 7: syntax error near unexpected token `('
./permute: line 7: `void permute(int level) {'

另外,當我嘗試使用 gcc 時,我收到分段錯誤錯誤:

$ mv permute permute.c
$ gcc permute.c -o permute.bin
$ chmod 755 permute.bin 
$ ./permute.bin 
Segmentation fault (core dumped)

答案1

看起來您最初將 C 文件命名為permute;當make失敗時,您嘗試使用 shell 執行它,這導致了所有這些語法錯誤(因為 shell 不知道如何執行 C 程式碼)。

在第二種情況下,您點擊了評論:

//必須提供長度(integer < sizeof(buffer)==50)作為第一個參數;

//否則會崩潰並燒毀

因為您沒有向程式提供第一個(或任何)參數。嘗試./permute.bin 10

答案2

在第一種情況下,看起來您將 C 程式碼儲存為permute然後嘗試執行

make CFLAGS=-O3 permute && time ./permute 5 >/dev/null

由於 沒有 的Makefile目標make,因此在列印資訊性訊息時它沒有錯誤地退出,

對於“排列”無需執行任何操作。

由於make未傳回錯誤代碼,因此time ./permute 5 >/dev/null執行該命令的第二部分 ( )。由於permute它是原始程式碼而不是可執行二進位文件,因此它被解釋為 shell 腳本,從而產生以下輸出:

./permute: line 3: //global: No such file or directory
./permute: line 4: const: command not found
./permute: line 5: char: command not found
./permute: line 7: syntax error near unexpected token `('
./permute: line 7: `void permute(int level) {'

更好的說明是將 C 原始程式碼儲存到permute.c然後執行以下命令來編譯它(並連結到所需的庫檔案):

gcc -O3 -o permute permute.c

這將創建permute一個可以運行的可執行二進位文件,例如:

./permute 2

相關內容