【发布时间】:2017-11-15 07:36:42
【问题描述】:
我构建了以下 C 示例,试图模拟可用于小型 ARM 微控制器的简单通用驱动程序代码:
#include <stdio.h>
#include <string.h>
typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);
typedef struct {
generic_func_t init;
generic_func_t open;
generic_func_t read;
generic_func_t write;
generic_func_t close;
generic_func_t exit;
} driver_t;
void USB_init(uint8_t x)
{
/* here body of this f-n */
printf("USB_open 0x%x\n", x);
}
void USB_open(uint8_t x)
{
/* here body of this f-n */
printf("USB_open 0x%x\n", x);
}
void USB_read(uint8_t x)
{
/* here body of this f-n */
printf("USB_read 0x%x\n", x);
}
void USB_write(uint8_t x)
{
/* here body of this f-n */
printf("USB_write 0x%x\n", x);
}
void USB_close(uint8_t x)
{
/* here body of this f-n */
printf("USB_close 0x%x\n", x);
}
void USB_exit(uint8_t x)
{
/* here body of this f-n */
printf("USB_close 0x%x\n", x);
}
typedef struct driver_t USB_driver;
#if 1
USB_driver.init = &USB_init;
USB_driver.open = &USB_open;
USB_driver.read = &USB_read;
USB_driver.write = &USB_write;
USB_driver.close = &USB_close;
USB_driver.exit = &USB_exit;
#endif
#if 1
void main(void) {}
#endif
#if 0
void main(void) {
USB_driver.init(0x01);
USB_driver.open(0x02);
USB_driver.read(0x03);
USB_driver.write(0x04);
USB_driver.close(0x05);
USB_driver.exit(0x06);
}
#endif
出现如下错误:
[user@localhost fn-ptr]$ emacs fn-ptr.c
(emacs:4983): Gtk-WARNING **: Allocating size to Emacs 0xdb4270 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
[user@localhost fn-ptr]$ gcc fn-ptr.c
fn-ptr.c:78:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.init = &USB_init;
^
fn-ptr.c:79:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.open = &USB_open;
^
fn-ptr.c:80:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.read = &USB_read;
^
fn-ptr.c:81:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.write = &USB_write;
^
fn-ptr.c:82:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.close = &USB_close;
^
fn-ptr.c:83:11: error: expected identifier or ‘(’ before ‘.’ token
USB_driver.exit = &USB_exit;
^
[user@localhost fn-ptr]$
这里的问题是:我应该怎么做才能使这段代码工作,因为下面这个代码构建的单函数指针示例可以完美地工作:
typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);
generic_func_t init;
void USB_init(uint8_t x)
{
/* here body of this f-n */
printf("USB_open 0x%x\n", x);
}
init = &USB_init;
【问题讨论】:
-
typedef 是这里令人困惑的地方吗?您是否打算在
typedef struct driver_t USB_driver;行声明一个 USB_driver 变量? -
init = &USB_init;不,这在标准 C 中不起作用。你不能在文件范围内运行代码,你只能在那里声明变量。 -
乔,你是完全正确的,同样! typedef struct driver_t USB_driver;将 USB_driver 定义为类型,而非变量。我以正确的方式预定义了它,所以一切都好!正如我们所说,已经有 7 年没有做嵌入式 C 了,但我很快就恢复了理智。现在,一切正常! :-)
-
Lundin,我犯了这个愚蠢的错误,因为我尝试了其他方法(将结构预定义为 .init 等),但情况突然失控了,我迷路了。 :-((
标签: c function-pointers