Kuan Kuan - 2 years ago 125
Linux Question

No idea how to use popt library


Thanks for help.

I am new to C option parsing, for now, what I want is to use popt library to parsing the each argument and prnit them out.

#include <iostream>
#include <string>
#include <cstring>
#include <popt.h>

using namespace std;

int main(int argc, const char* argv[]){

char* dt1;
char* dt2;

struct poptOption {
const char * longName; /* may be NULL */
char shortName; /* may be ’\0’ */
int argInfo;
void * arg; /* depends on argInfo */
int val; /* 0 means don’t return, just update flag */
char * descrip; /* description for autohelp -- may be NULL */
char * argDescrip; /* argument description for autohelp */
struct poptOption optionsTable[]={
{"start",'s',POPT_ARG_STRING,dt1,'s',"The date format should like YYYY-MM-DD.",0},
{"end",'e',POPT_ARG_STRING,dt2,'e',"The date format should like YYYY-MM-DD.",0},
//~ {NULL,0,0,NULL,0}

poptContext optCon;
optCon = poptGetContext (0, argc, argv, optionsTable, 0);

const char* portname = poptGetArg(optCon);
return 0;

When I compile it, I got error llike:

test.cpp: In function ‘int main(int, const char**)’

test.cpp:27: warning: deprecated conversion from string constant to ‘char*’

test.cpp:27: warning: deprecated conversion from string constant to ‘char*’

test.cpp:30: error: cannot convert ‘main(int, const char**)::poptOption*’ to ‘const poptOption*’ for argument ‘4’ to ‘poptContext_s* poptGetContext(const char*, int, const char**, const poptOption*, unsigned int)’

Answer Source

I don't think you should be defining the struct poptOption in your program. That struct should be defined for you in the popt include file. Try removing that struct definition.

Note, I think you also need to uncomment this line:

    //~ {NULL,0,0,NULL,0}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download