c - 将多个声明链接到同一定义

标签 c

我已经用 C(不是 C++)实现了一个链表,它存储指向数据的指针。我希望它的函数有多个声明(以提供类型安全),但每个声明都链接到相同的定义(因为指向不同数据类型的指针之间没有实际区别,所以使用相同的代码可以减少空间)。

有没有人对如何实现这一目标(或任何更好的方法)有任何想法?可移植解决方案显然是最好的,但我真的只需要在 GCC 中工作的东西。

最佳答案

我相信您可以使用函数原型(prototype)的 typedef 来实现这一点,并且 将通用解决方案(处理 void*)转换为特定原型(prototype)。这对于编译应该是安全的,因为所有指针的大小都相同。

考虑这个例子:

do_something.h:

typedef void (*do_something_with_int_t)(int *i);
extern do_something_with_int_t do_something_with_int;

typedef void (*do_something_with_string_t)(char *s);
extern do_something_with_string_t do_something_with_string;

do_something.c

#include "do_something.h"

void do_something_generic(void* p) {
    // Do something generic with p
}


do_something_with_int_t do_something_with_int =
    (do_something_with_int_t)do_something_generic;

do_something_with_string_t do_something_with_string =
    (do_something_with_string_t)do_something_generic;

只要 do_something_generic 是真正的数据类型不可知论者(即 真的 p 指向什么并不重要)那么这将是好的。

关于c - 将多个声明链接到同一定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16704220/

相关文章:

c - 在 Windows 上关闭子进程的非标准匿名管道句柄的最佳方法是什么?

c - 当我在链接列表中插入任何值之前选择删除选项时,我收到段错误错误

c - getpass 函数的更好替代方案

python - 是否可以从 C/C++ 调用 numba jited 函数?

c - 将字符串写入动态分配的数组

c - free功能好像不行

c++ - 未定义的函数引用,当在 Windows 上使用 if 定义时(在 Linux 上可以)

c - 图形处理库

c - 使用长的位列表

计算具有 sin/cos LUT 的 tan