cunixcommand-lineargvargc

Unix/C command line arguments: Every single function has the same error what am I doing wrong?


I am supposed to take in arguments from the command line, to build a sample Unix-style 'ls' style program that lists the directory contents.

I have pre-built functions given to me and I have to separate the code down into modularized header and c files for each individual function and create a makefile.

The makefile will run and gives these warnings:

-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

Here is do_ls.h:

'''

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


#endif

'''

Errors:

-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

main:

#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 );
            }
    }

Solution

  • The do_ls function expects an array of char *, but when you call it you only pass in a single char *. This is what the warning in the initial call to make is complaining about. This argument mismatch invokes undefined behavior.

    Try calling it like this:

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