![](/img/trans.png)
[英]Initializing a member of a struct to a function pointer without knowing the returned type
[英]Initializing a member from struct to the direction of an external function
假設我有這個
typedef struct qwerty {
void *f;
} qwerty_t;
我想這樣做
static qwerty_t x = {
.f = (void *)some_external_function
};
我收到error: initializer element is not constant
因為(如果我理解正確的話)在編譯時some_external_function
的方向未知。
如果那不是錯誤的正確解釋,請解釋是什么。
另外,如何將.f
初始化為該函數的方向?
從評論到問題:
我不確定它是否是確定的,但是... 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;
}
當像這樣編譯“特別大驚小怪”時,您會收到一些警告:
$ 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;
^
$
警告是精確的-但是POSIX指出,函數指針的大小必須與數據指針的大小相同(而C標准允許它們有所不同)。 如果沒有-pedantic
,則不會發出警告。
將代碼分成兩個文件,一個文件定義為x
和main()
,另一個文件定義為some_external_function()
,並且進行編譯和鏈接不會產生錯誤,也不會產生新警告。
這可能是因為您要為x定義static關鍵字。 基本上,C要求您將靜態存儲與常量表達式或值關聯。 甚至如下所示的簡單操作也會給您同樣的錯誤:
int main() {
int y = 10;
static int z = y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.