【发布时间】:2016-01-30 02:52:23
【问题描述】:
当我尝试在命令行中将 -H 作为标志传递时,为什么总是出现设置错误? -h (help) 运行良好,但 -H(header) 每次都搞砸了。
我还有一个 main 函数,它通过传递 argc 和 argc 来调用 parse_command_line。
bool 定义为 bool header = false;
文件是char** file = NULL;
以及我拥有文件的原因+=1;在代码中是这样编译的,因为我使用了一个将所有警告更改为错误的生成文件。
#include "parse.h" /* prototypes for exported functions */
#include "../main/unused.h"
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <stdint.h>
int
parse_command_line (int argc, char **argv, bool *header, char **file)
{
int oc = 0;
file += 1;
bool help = false;
struct option long_options[] =
{
{"header", no_argument, NULL, 'H'},
{"help", no_argument, NULL, 'h'},
{0, 0, 0, 0}
};
while ((oc = getopt_long(argc, argv, "+Hh", long_options, NULL)) != -1)
{
printf("The value of oc = %d\n", oc);
switch(oc)
{
case 'h':
help = true;
break;
case 'H':
printf("inside case H");
*header = true;
break;
case '?':
fprintf(stderr, "Unknown flag = -%c, type -h or --help for help!\n", optopt);
exit(EXIT_FAILURE);
break;
default:
break;
}
}
printf("Out of loop"); if (optind+1 != argc)
{
fprintf(stderr, "Uh oh, invalid input! Try again with -h or --help for help!\n");
exit(EXIT_FAILURE);
}
if (help)
{
printf("\nHaving some trouble? Let me show you the ropes!\n\n");
printf("Format: ydi <option(s)> mini-elf-file\n\n");
printf("Here's your options:\n");
printf("-h --help Display usage\n");
printf("-H --header Show the Mini-Elf header\n");
exit(1);
}
if (header)
{
printf("Inside HEader");
FILE *file;
uint16_t nums[6];
file = fopen(argv[optind], "r");
#define STRUCT_ITEMS 7
fread(nums, 16, 6, file);
int cur_print;
for (cur_print = 0; cur_print < STRUCT_ITEMS; cur_print++)
{
printf("%d ", nums[cur_print]);
}
}
return 0;
}
我的 parse.h 文件如下:
#ifndef __PARSE_COMMAND_LINE__
#define __PARSE_COMMAND_LINE__
#include <stdbool.h>
int parse_command_line (int argc, char **argv, bool *header, char **file);
#endif
还有其他文件,例如 elf.h 和 elf.c,我还没有实现,此时根本没有调用它们,这让我相信它们不会成为问题,也不需要发布小的 2 行文件。我的主要功能如下:
#include <stdio.h> /* standard I/O */
#include <stdlib.h>
#include "unused.h" /* UNUSED macro */
#include "../cmdline/parse.h" /* command line parser */
#include "../y86/elf.h" /* Mini-ELF format */
int
main (int argc UNUSED, char **argv UNUSED)
{
printf ("Congratulations, you have compiled your source code!\n");
bool header = false;
char **file = NULL;
parse_command_line (argc, argv, &header, file);
return 0;
}
而unused.h文件(因为编译器会使未使用的变量成为错误而不是警告)如下:
#ifndef __UNUSED__
#define __UNUSED__
#define UNUSED __attribute__ ((unused))
#endif
【问题讨论】:
-
其余代码在哪里?从一个疯狂的猜测中,我会说将
*header更改为header。 -
@Mike 不幸的是我得到了这个错误:赋值使指针从整数没有强制转换 [-Werror],不过我添加了其余的代码
-
如果将 oc 声明为 char 而不是 int 并将 getopt_long 的结果转换为 char 会发生什么?
-
@Mike 它仍然是段错误(核心转储)
-
为什么OP删除了这个问题?它有一个负数,但没有人将其标记为“关闭”。现在,所有的 cmets 和给定的答案对任何人都没有用:(任何高级用户都可以取消删除它吗?
标签: c segmentation-fault switch-statement getopt getopt-long