[英]Initializing a member from struct to the direction of an external function
Let's say I have this 假设我有这个
typedef struct qwerty {
void *f;
} qwerty_t;
and I want to do this 我想这样做
static qwerty_t x = {
.f = (void *)some_external_function
};
I'm getting error: initializer element is not constant
because (if I understand correctly) the direction of some_external_function
is unknown when I'm compiling. 我收到
error: initializer element is not constant
因为(如果我理解正确的话)在编译时some_external_function
的方向未知。
If that is not the correct explanation of the error, please explain what is. 如果那不是错误的正确解释,请解释是什么。
Also, how can I initialize .f
to the direction of that function? 另外,如何将
.f
初始化为该函数的方向?
From the comments to the question: 从评论到问题:
You don't show the declaration of
some_external_function
?您没有显示
some_external_function
的声明吗? If, for example, it is itself a function pointer, not an actual function, you would get that error.例如,如果它本身是一个函数指针,而不是实际的函数,则会出现该错误。 — Jonathan Leffler
— 乔纳森·勒夫勒
Indeed, you're right.
确实,你是对的。 I was doing exactly that.
我就是这么做的。 — alexandernst
— 亚历山大
I'm not sure it's definitive, but... GCC 4.8.1 on Mac OS X 10.8.4 accepts this code OK: 我不确定它是否是确定的,但是... Mac OS X 10.8.4上的GCC 4.8.1接受以下代码,确定:
extern int some_external_function(int, int);
typedef struct qwerty {
void *f;
} qwerty_t;
static qwerty_t x = {
.f = (void *)some_external_function
};
int main(void)
{
int i = 1;
int j = 2;
int (*f)(int, int) = (int (*)(int, int))x.f;
return f(i, j);
}
int some_external_function(int i, int j)
{
return i + j;
}
When compiled 'extra fussy' like this, you get some warnings: 当像这样编译“特别大惊小怪”时,您会收到一些警告:
$ gcc -std=c99 -Wall -Wextra -pedantic fp.c -o fp
fp.c:8:14: warning: ISO C forbids conversion of function pointer to object pointer type [-Wpedantic]
.f = (void *)some_external_function
^
fp.c: In function ‘main’:
fp.c:15:26: warning: ISO C forbids conversion of object pointer to function pointer type [-Wpedantic]
int (*f)(int, int) = (int (*)(int, int))x.f;
^
$
The warnings are pedantically accurate — but POSIX states that the size of a function pointer must be the same as the size of a data pointer (whereas the C standard permits them to differ). 警告是精确的-但是POSIX指出,函数指针的大小必须与数据指针的大小相同(而C标准允许它们有所不同)。 Without
-pedantic
, there are no warnings. 如果没有
-pedantic
,则不会发出警告。
Splitting the code into two files, one with definitions of x
and main()
and the other with the definition of some_external_function()
, and compiling and linking yields no errors and no new warnings. 将代码分成两个文件,一个文件定义为
x
和main()
,另一个文件定义为some_external_function()
,并且进行编译和链接不会产生错误,也不会产生新警告。
This is likely because you are defining the static keyword for the x. 这可能是因为您要为x定义static关键字。 Basically, C requires you to associate a static storage with a constant expression or value.
基本上,C要求您将静态存储与常量表达式或值关联。 Even something as simple as below would give you the same error:
甚至如下所示的简单操作也会给您同样的错误:
int main() {
int y = 10;
static int z = y;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.