공용체 및 구조체 초기화 질문

kkchlove의 이미지

typedef struct {
const char *name;
int flags;
union {
void (*func_arg)(const char *); //FIXME passing error code as int return would be nicer then exit() in the func
int *int_arg;
char **str_arg;
float *float_arg;
int (*func2_arg)(const char *, const char *);
int64_t *int64_arg;
} u;
const char *help;
const char *argname;
} OptionDef;

위와 같은 구조체가 잇는데요...

아래와 같이 컴파일하면... 에러가... ㅜㅜ

static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {(void*)show_license}, "show license" },
{ "h", OPT_EXIT, {(void*)show_help}, "show help" },

};

에러는 다음과 같습니다.

error: a value of type "void *" cannot be used to initialize an entity of type "void (*)(const char *)"
1> { "L", OPT_EXIT, {(void*)show_license}, "show license" }

어떻게 해야할까요?

Scarecrow의 이미지

static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {(void (*)(const char *))show_license}, "show license" },
{ "h", OPT_EXIT, {(void (*)(const char *))show_help}, "show help" },
 
};

static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {(int (*)(const char *, const char *))show_license}, "show license" },
{ "h", OPT_EXIT, {(int (*)(const char *, const char *))show_help}, "show help" },
 
};

같은게 의도하려던 표현이 아니었을까 하는 짐작이...

라스코니의 이미지

static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {show_license}, "show license" },
{ "h", OPT_EXIT, {show_help}, "show help" },

};

으로 하면 안되나요? 어짜피 union 으로 되어 있어서,,, 캐스팅이 호출시에 필요한데...

amir173의 이미지

일반적으로 union 각 field 의 초기화는 동시에 이루어 질 수 없고 위와 같이 선언과 동시에 초기화 할 시에는
가장 먼저 기술되어있는 field 의 값으로 초기화 된다고 알고 있습니다. 그래서 가장 먼저 선언 되어있는

void (*func_arg)(const char *);

가 초기화될수 있는 형태인데 아래 코드를 보면
static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {(void*)show_license}, "show license" },
{ "h", OPT_EXIT, {(void*)show_help}, "show help" },
};

(void*) 로 형변환 시켜버려서 문제가 생기는 것입니다.
show_license 는 다음의 형태가 되어야 문제가 없어집니다.
void (*show_license)(const char*);
void show_license( const char* );

show_license 를 수정하신후 다음과 같이 초기화 하시면 됩니다.
static const OptionDef options[] = {
/* main options */
{ "L", OPT_EXIT, {show_license}, "show license" },
{ "h", OPT_EXIT, {show_help}, "show help" },
 
};