如何为具有多种实现的接口函数创建弱别名默认定义

问题描述

客观

  • 使用接口中使用的每个函数指针的认实现创建通用接口。
    • 这在一定程度上是需要的,以便在使用接口函数指针时我们永远不会有空指针引用。
  • 支持此接口的多个“实例”(尤其是此接口的不同实现)。
    • 这意味着我们应该能够创建类型A的通用接口实例和类型B的通用接口实例,其中任一实例都可以使用认定义来具有函数指针。

结果

我为认实现使用了弱别名,但是似乎这不允许我对接口进行多个实现,并且当我尝试以两种方式编译它们时,都会遇到static declaration follows non-static declaration错误删除static关键字会导致multiple deFinition错误

示例代码

我的界面,特定的和认的实现可以简化为以下示例。

dfltDef_Header.h

#ifndef __DEFAULTDEF_H_
#define __DEFAULTDEF_H_
#include <stdint.h>
#include <stdbool.h>
#define _weak_alias(old,new) \
        extern __typeof(old) new __attribute__((weak,alias(#old)))

typedef struct {
    int  (*getVal)(void);
    bool (*isTrue)(void);
} myIF_t;

int getVal(void);
bool isTrue(void);

#endif // __DEFAULTDEF_H_

dfltDef_impl.c

#include <stdint.h>
#include <stdbool.h>
#include "dfltDef_header.h"

bool dflt_isTrue(void) {
    return true;
}

int dflt_getVal(void) {
    return 3;
}

_weak_alias(dflt_isTrue,isTrue);

_weak_alias(dflt_getVal,getVal);

someInterfaceImpl.h

#ifndef __SOMEINTERFACEIMPL_H_
#define __SOMEINTERFACEIMPL_H_
#include "dfltDef_header.h"

myIF_t *getInterface(void);

#endif // __SOMEINTERFACEIMPL_H_

someInterfaceImpl.c

#include "someInterfaceImpl.h"
#include "dfltDef_header.h"

bool isTrue(void) {
    return false;
}

static myIF_t thisInterface = {
    .getVal = getVal,.isTrue = isTrue,};

myIF_t *getInterface(void) {
    return &thisInterface;
}

anotherInterfaceImpl.h

#ifndef __ANOTHERINTERFACEIMPL_H_
#define __ANOTHERINTERFACEIMPL_H_
#include "dfltDef_header.h"

myIF_t *getotherInterface(void);
#endif // __ANOTHERINTERFACEIMPL_H_

anotherInterfaceImpl.c

#include "anotherInterfaceImpl.h"
#include "dfltDef_header.h"

static int getVal(void) {
    return 1;
}

static myIF_t thisInterface = {
    .getVal = getVal,};

myIF_t *getotherInterface(void) {
    return &thisInterface;
}

dflDef_App.c

#include "dfltDef_header.h"
#include "someInterfaceImpl.h"
#include "anotherInterfaceImpl.h"

int main() {
    /* DFLT_FUNC(getVal) */
    myIF_t *IF = getInterface();
    printf("%d %d\n",IF->isTrue(),IF->getVal());

    myIF_t *otherIF = getotherInterface();
    printf("%d %d\n",otherIF->isTrue(),otherIF->getVal());

    return 0;
}

使用编译时

gcc dflDef_App.c someInterfaceImpl.c anotherInterfaceImpl.c dfltDef_impl.c -o dfltExample

我得到以下信息:

anotherInterfaceImpl.c:4:12: error: static declaration of ‘getVal’ follows non-static declaration
    4 | static int getVal(void) {
      |            ^~~~~~
In file included from anotherInterfaceImpl.h:3,from anotherInterfaceImpl.c:1:
dfltDef_header.h:13:5: note: prevIoUs declaration of ‘getVal’ was here
   13 | int getVal(void);
      |     ^~~~~~

关键问题

  • 是否可以使用静态函数定义覆盖弱别名?
  • 我可以使一个强符号(通过静态库或其他方式)对其他符号隐藏吗?
  • 这是完全不可能还是不好的做法?

以这样的方式执行此操作非常好,即只能通过接口使用接口函数定义,如果未定义接口,那么我们将使用认定义。任何帮助/建议都将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)