要运行我的程序,unix命令行是" p2 -s input.txt"
通常(没有makefile)检查标志== -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
答案 0 :(得分: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;
}
另外,您可以手动比较每个字符,因为标志字符串很短。
#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;
}
答案 1 :(得分:1)
测试
if(argv[1] == "-s")
在C中不起作用。 C ++经常被重载以便直观地工作,但C的作用是:
argv[1]
的值与"-s"
argv[]
所在位置的一个条目,由C运行时库或操作系统设置)。if
表达式的计算结果为0(零)。else
分支被采用。使用string.h函数strcmp()
来比较给定地址的字符串。在C中,字符串是由ascii NUL终止的字符序列。
另请注意,您main()
的定义存在缺陷,如MikeCAT所述。
答案 2 :(得分:0)
解析命令行选项是一个相当完善的问题 - 您可以使用getopt()
或libpopt(https://directory.fsf.org/wiki/Popt)。 @MikeCAT解释了字符串比较中的其他问题。