对于收到的编译器警告以及如何解决它们,我有些困惑。以下是错误和相关的代码片段:

cmds的声明(与大多数命令有关):

 23: static char **cmds[] = { cmd0, cmd1, cmd2, cmd3, cmd4 };
 24: static int   ncmds = sizeof(cmds) / sizeof(cmds[0]);


pipeline.c: In function âexec_nth_commandâ:
pipeline.c:41: warning: declaration of âncmdsâ shadows a global declaration
pipeline.c:24: warning: shadowed declaration is here
pipeline.c:41: warning: declaration of âcmdsâ shadows a global declaration
pipeline.c:23: warning: shadowed declaration is here

 41: static void exec_nth_command(int ncmds, char ***cmds)

pipeline.c: In function âexec_pipe_commandâ:
pipeline.c:68: warning: declaration of âncmdsâ shadows a global declaration
pipeline.c:24: warning: shadowed declaration is here
pipeline.c:68: warning: declaration of âcmdsâ shadows a global declaration
pipeline.c:23: warning: shadowed declaration is here

 68: static void exec_pipe_command(int ncmds, char ***cmds, Pipe output)

pipeline.c: In function âexec_pipelineâ:
pipeline.c:79: warning: declaration of âncmdsâ shadows a global declaration
pipeline.c:24: warning: shadowed declaration is here
pipeline.c:79: warning: declaration of âcmdsâ shadows a global declaration
pipeline.c:23: warning: shadowed declaration is here

 79: static void exec_pipeline(int ncmds, char ***cmds)

pipeline.c:82: warning: ISO C90 forbids mixed declarations and code


 82: pid_t pid;

pipeline.c: In function âerr_usageâ:
pipeline.c:141: warning: declaration of âusestrâ shadows a global declaration
pipeline.c:26: warning: shadowed declaration is here

  26: static char const usestr[] = "[-f filename]";
 141: static void err_usage(char const *usestr)

最佳答案

警告说您的本地名称会覆盖具有相同名称的其他变量。所以

pipeline.c:41: warning: declaration of âncmdsâ shadows a global declaration


ncmds参数被static char **cmds[] =变量隐藏,使得该参数不可访问。

解决这些问题的方法是简单地为参数或变量选择一个不同的名称。我会更改您不常使用的代码的名称,因此您不必更改太多代码。您也可以忽略该警告,但其原因是因为稍后查看代码或在该函数中编写新内容时,当您指的是另一个时,您可能会意外地引用其中一个,因为相同的名称可能会造成混淆。

pipeline.c:82: warning: ISO C90 forbids mixed declarations and code


这是因为在较早的样式C中,不允许在范围顶部以外的任何地方声明变量。实际上,这样做没有问题,实际上,通常最好将变量声明为尽可能靠近使用点,因此在这里我不会更改代码。相反,请尝试使用-std=c99进行编译-标准的较新版本允许这样做。

关于c - 令人困惑的编译器警告,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20035470/

10-12 18:04
查看更多