【问题标题】:Unix/C command line arguments: Every single function has the same error what am I doing wrong?Unix/C 命令行参数:每个函数都有相同的错误我做错了什么?
【发布时间】:2020-05-31 09:09:42
【问题描述】:

我应该从命令行接受参数,以构建一个列出目录内容的示例 Unix 风格的 'ls' 风格的程序。

我有预建的函数,我必须为每个单独的函数将代码分成模块化的头文件和 c 文件,并创建一个 makefile。

makefile 将运行并给出以下警告:

-bash-3.2$ make run
gcc -c main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type

这里是 do_ls.h:

'''

#ifndef DO_LS
#define DO_LS
                void do_ls( char*[] );


#endif

'''

错误:

-bash-3.2$ gcc main.c
main.c: In function ‘main’:
main.c:18: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
main.c:23: warning: passing argument 1 of ‘do_ls’ from incompatible pointer type
/tmp/cc8Q7153.o: In function `main':
main.c:(.text+0x1b): undefined reference to `do_ls'
main.c:(.text+0x47): undefined reference to `do_ls'
collect2: ld returned 1 exit status

主要:

#include        <stdio.h>
#include        <sys/types.h>
#include        <dirent.h>
#include        "do_ls.h"


    int main(int ac, char *av[])
    {
     if ( ac == 1 )
            do_ls(".");

     else
            while ( --ac ){
                    printf("%s:\n", *++av );
                    do_ls( *av );
            }
    }

【问题讨论】:

  • 请在do_ls.h发代码。
  • 如果您在没有任何命令行标志的情况下调用gcc,它会尝试生成一个可执行文件。除非:(1)main() 已定义,并且(2)您使用的每个函数都已定义(而不仅仅是声明),否则它不能这样做。这就是那些链接器错误试图告诉你的。这与您的段错误无关,尽管您第一次编译中的错误参数类型警告可能是相关的。
  • 请阅读有关如何创建 MCVE (Minimal, Complete, Verifiable Example)(或 MRE 或 SO 现在使用的任何名称)或 SSCCE (Short, Self-Contained, Correct Example) 的信息。您提供的不是 MCVE — 我们需要查看 do_ls.h,我们不需要知道 dostat.hshow_file_info.hmode_to_letters.huid_to_name.hgid_to_name.h 的存在(以及除了&lt;stdio.h&gt; 之外,您不需要任何系统标头来显示您显示的main() 函数)。

标签: c unix command-line argv argc


【解决方案1】:

do_ls 函数需要一个 char * 数组,但是当你调用它时,你只传入一个 char *。这就是最初调用make 时所抱怨的警告。此参数不匹配调用undefined behavior

试着这样称呼它:

if ( ac == 1 ) {
    char *args[] = { ".", NULL };
    do_ls(args);
} else {
    do_ls(av+1);
}

【讨论】:

  • 谢谢。最初这样做我仍然得到一个不兼容的指针类型。如果我为 do_ls.h 这样做,我是否必须重新定义标头和函数原型?
  • @amorphous_solid 大概,do_ls 已经给了你,所以你不应该改变它。相反,您需要确保传入的内容与预期相符。
  • 我会说它现在正在使用此修复程序编译和输出正确的内容,而不管不兼容的指针类型错误如何。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多