2016-02-26 46 views
1

運行我的程序的UNIX命令行是「P2 -s input.txt的」的Makefile C命令行參數

(通常不生成文件),以檢查標誌== -s我有我的UNIX輸入是 - a.out的-s input.txt中,和我的main.c是:

int main(int argc, char argv[]) 
{ 
    if(argv[1] == "-s") 
    { 
     printf("The flag is -s\n"); 
    } 
    else 
    { 
     printf("The flag is not -s"); 
    } 
    return 0; 
} 

現在,當我用一個makefile代碼這一點,我應該改變我如何檢查該標誌?或者我需要更改main.c的參數?我的Makefile:

all: p2 
p2: main.o functions.o 
    gcc -o p2 main.o functions.o 
main.o: main.c 
    gcc -c main.c 
functions.o: functions.c 
    gcc -c functions.c 
clean: 
    rm -f *.o core 
+3

我想你應該使用'strcmp(argv [1],「-s」)== 0'而不是'argv [1] ==「-s」'。 – MikeCAT

+0

你的問題不清楚。爲什麼makefile會影響你編寫解析程序命令行的代碼? makefile可以幫助你構建程序。然後你就像平常一樣運行程序。 – kaylum

+0

謝謝@mikeCAT。我以爲我曾嘗試過,我認爲它給了我一個比較指針和整數的錯誤。謝謝我感謝您的幫助! – John

回答

1

測試

if(argv[1] == "-s") 

像它看起來確實不是在C工作。 C++經常超載,這直觀地工作,但做什麼C是:

  1. argv[1]的值進行比較的平等的"-s"
  2. 第一的價值值接近堆棧的頂部一些地址(從C運行時庫或操作系統設置的argv[]所在位置開始的一個條目)。
  3. 第二個值是一個指向字符串常量的指針。
  4. 地址不相等,因此if表達式的計算結果爲0(零)。
  5. 所以else分支被採取。

使用string.h函數strcmp()來比較給定地址處的字符串。在C中,一個字符串是由ascii NUL結尾的一系列字符。

此外,請注意您的main()的定義存在缺陷,如MikeCAT所述。

+0

仔細查看代碼。第二個參數是'char argv []',而不是'char * argv []'。因此'argv [1]'不是一個地址。 – MikeCAT

+0

@MikeCAT:嗨!我錯過了。我希望大多數編譯器也會用'main()'的一個隱含原型來說明它。 – wallyk

1

是的,你應該改變你如何檢查標誌不管你是否使用Makefile,因爲它不是標準的和沒有機會的成功之路在C.

比較字符串

您應該使用strcmp()比較字符串

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

/* correct the type of second argument to the standard one, or strcmp() won't work */ 
int main(int argc, char *argv[]) 
{ 
    if(strcmp(argv[1] "-s") == 0) 
    { 
     printf("The flag is -s\n"); 
    } 
    else 
    { 
     printf("The flag is not -s"); 
    } 
    return 0; 
} 

Altenatively,你可以因旗串短手動比較每個字符。

#include <stdio.h> 

/* correct the type of second argument to the standard one, or strcmp() won't work */ 
int main(int argc, char *argv[]) 
{ 
    if(argv[1][0] == '-' && argv[1][1] == 's' && argv[1][2] == '\0') 
    { 
     printf("The flag is -s\n"); 
    } 
    else 
    { 
     printf("The flag is not -s"); 
    } 
    return 0; 
} 
0

解析命令行選項是一個相當好解決的問題 - 您可以使用getopt()或libpopt(https://directory.fsf.org/wiki/Popt)。 @MikeCAT解釋了字符串比較中的其他問題。