如何指示 gcc 像 g++ 那样警告我有关无效函数指针转换的信息?
How to instruct gcc to warn me about invalid function pointer conversion just as g++ would do?
我如何指示 gcc 警告我无效的函数指针转换,就像 g++ 对以下代码所做的那样?
还有.. 为什么 gcc 不警告我?将指向 a 的指针传递给 do_something() 时会发生什么?
#include <stdio.h>
typedef void (*void_func_t) ();
typedef void (*void_int_func_t) (int, int, int);
void do_something(void_func_t f)
{
void_int_func_t foo = f;
foo(1,2,3);
}
void a()
{
printf("a\n");
}
void b(int one, int two, int three)
{
printf("%i, %i, %i\n", one, two, three);
}
int main()
{
do_something(a);
do_something(b);
return 0;
}
输出:
➜ gcc -W -Wall -Werror func.c
➜ ./a.out
a
1, 2, 3
c++,但是会警告/给出错误
g++ -W -Wall -Werror func.c
func.c: In function ‘void do_something(void_func_t)’:
func.c:8:27: error: invalid conversion from ‘void_func_t {aka void (*)()}’ to ‘void_int_func_t {aka void (*)(int, int, int)}’ [-fpermissive]
func.c: In function ‘int main()’:
func.c:25:19: error: invalid conversion from ‘void (*)(int, int, int)’ to ‘void_func_t {aka void (*)()}’ [-fpermissive]
func.c:6:6: error: initializing argument 1 of ‘void do_something(void_func_t)’ [-fpermissive]
带空括号的函数原型是过时的1 功能。不要使用它。
如果您使用正确的声明,您将收到警告:
typedef void(*void_func_t)(void);
由于这个旧功能,类型 void(*)()
和 void(*)(int, int, int)
是兼容的。前一种类型采用未指定数量的参数。这是双重问题,因为没有来自编译器的警告,如果您使用不正确数量的参数调用该函数,则行为未定义。
与 C 不同,在 C++ 中,空括号表示函数不带参数,因此 void(*)()
等同于 void(*)(void)
.
1(引自:ISO/IEC 9899:201x 6.11.6 函数声明符
1)
使用带有空括号的函数声明符(不是原型格式参数
类型声明符)是一个过时的特性。
我如何指示 gcc 警告我无效的函数指针转换,就像 g++ 对以下代码所做的那样?
还有.. 为什么 gcc 不警告我?将指向 a 的指针传递给 do_something() 时会发生什么?
#include <stdio.h>
typedef void (*void_func_t) ();
typedef void (*void_int_func_t) (int, int, int);
void do_something(void_func_t f)
{
void_int_func_t foo = f;
foo(1,2,3);
}
void a()
{
printf("a\n");
}
void b(int one, int two, int three)
{
printf("%i, %i, %i\n", one, two, three);
}
int main()
{
do_something(a);
do_something(b);
return 0;
}
输出:
➜ gcc -W -Wall -Werror func.c
➜ ./a.out
a
1, 2, 3
c++,但是会警告/给出错误
g++ -W -Wall -Werror func.c
func.c: In function ‘void do_something(void_func_t)’:
func.c:8:27: error: invalid conversion from ‘void_func_t {aka void (*)()}’ to ‘void_int_func_t {aka void (*)(int, int, int)}’ [-fpermissive]
func.c: In function ‘int main()’:
func.c:25:19: error: invalid conversion from ‘void (*)(int, int, int)’ to ‘void_func_t {aka void (*)()}’ [-fpermissive]
func.c:6:6: error: initializing argument 1 of ‘void do_something(void_func_t)’ [-fpermissive]
带空括号的函数原型是过时的1 功能。不要使用它。
如果您使用正确的声明,您将收到警告:
typedef void(*void_func_t)(void);
由于这个旧功能,类型 void(*)()
和 void(*)(int, int, int)
是兼容的。前一种类型采用未指定数量的参数。这是双重问题,因为没有来自编译器的警告,如果您使用不正确数量的参数调用该函数,则行为未定义。
与 C 不同,在 C++ 中,空括号表示函数不带参数,因此 void(*)()
等同于 void(*)(void)
.
1(引自:ISO/IEC 9899:201x 6.11.6 函数声明符
1)
使用带有空括号的函数声明符(不是原型格式参数
类型声明符)是一个过时的特性。