编译器警告 - 使用GCC的C函数重载 [英] Function overloading in C using GCC - compiler warnings
问题描述
我试图实现函数重载在 C ,我很接近。我使用C99所以在C11引入了 _Generic
关键字不能提供给我。我已经开发了一些工作code,但是当我编译它,我得到一对夫妇的警告。
I am attempting to implement function overloading in C, and I am very close. I am using C99 so the _Generic
keyword introduced in C11 is not available to me. I have developed some working code, but when I compile it I get a couple warnings.
的例子:
#include <stdio.h>
#define print(x) \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), int ), print_int(x) , \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), char[]), print_string(x), \
(void)0))
void print_int(int i) {
printf("int: %d\n", i);
}
void print_string(char* s) {
printf("char*: %s\n", s);
}
int main(int argc, char* argv[]) {
print(1);
print("this");
return 0;
}
编译生成以下警告:
Compiling creates the following warnings:
gcc overload.c -o main
overload.c: In function 'main':
overload.c:19: warning: passing argument 1 of 'print_string' makes pointer from integer without a cast
overload.c:20: warning: passing argument 1 of 'print_int' makes integer from pointer without a cast
有关更多一点的调试信息,这里是主要的功能是什么样子的preprocessor做工作后:
For a little more debugging information, here is what the main function looks like after the preprocessor does its work:
int main(int argc, char* argv[]) {
__builtin_choose_expr(__builtin_types_compatible_p(typeof(1), int ), print_int(1) , __builtin_choose_expr(__builtin_types_compatible_p(typeof(1), char[]), print_string(1), (void)0));
__builtin_choose_expr(__builtin_types_compatible_p(typeof("this"), int ), print_int("this") , __builtin_choose_expr(__builtin_types_compatible_p(typeof("this"), char[]), print_string("this"), (void)0));
return 0;
}
我怎样才能让编译警告消失,仍然有工作code?
How can I make the compilation warnings go away and still have working code?
推荐答案
在理论上,这应该工作:
In theory, this should work:
#define print(x) \
(__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), int ), print_int , \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(x), char[]), print_string, \
(void)0))(x))
它选择为 print_int
或 print_string
,然后应用所选择的功能, X
。
It chooses either print_int
or print_string
, then applies the chosen function to x
.
这篇关于编译器警告 - 使用GCC的C函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!