Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convenient practice to write/display help/usage info in a program written in C?

Tags:

c

I am writing a program in C which is like a console so that user can specify different commands to be executed(which are also defined by me). Just like the one below:

>cmd1 arg
(result blah blah blah)
>

and I want to display usage info which is like:

>help
Usage: cmd1 arg1 [arg2]
       cmd2 arg1 [arg2]
       cmd3 arg1 [arg2]
       ....

But I find it clumsy to define string or macro like "Usage: cmd1 arg1 [arg2] \n \t "... (and I am not sure it's OK or not). Is there some best practice to do so?

like image 364
onemach Avatar asked Oct 27 '25 05:10

onemach


2 Answers

The standard practice is to make a usage function that you can call when certain conditions are met (there were no arguments pass to the program, etc), like this:

void usage(void) {
    printf("Usage: cmd1 arg1 [arg2]\n"
           "       cmd2 arg1 [arg2]\n"
           "       cmd3 arg1 [arg2]\n"
           ...
           "       cmdn arg1 [arg2]\n"); // if the string is too long you'll have
                                         // to break it up into multiple printfs
}

int main(int argc, char** argv) {
    if (argc < 2) {
        usage(); 
        return 0;
    }

    // main program....
}
like image 161
Seth Carnegie Avatar answered Oct 29 '25 18:10

Seth Carnegie


If you're programming on/for a system that can use the gnu argp library, you'd do well to look into that. It makes it easier to process the arguments, and creates help/usage messages and options for you.

like image 23
Kevin Avatar answered Oct 29 '25 19:10

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!