typedef sturct
{
uint8_t element1;
uint8_t element2;
...
uint8_t element8;
uint8_t element9;
}chip_a_t;
bool chip_a_get_element1(chip_a_t* me);
bool chip_a_get_element2(chip_a_t* me);
...
bool chip_a_get_element8(chip_a_t* me);
bool chip_a_get_element9(chip_a_t* me);
chip_b.h
typedef sturct
{
uint8_t element_a;
uint8_t element_b;
...
uint8_t element_y;
uint8_t element_z;
}chip_b_t;
bool chip_b_get_element_a(chip_b_t* me);
bool chip_b_get_element_b(chip_b_t* me);
...
bool chip_b_get_element_y(chip_b_t* me);
bool chip_b_get_element_z(chip_b_t* me);
现在,假设我在程序中的程序逻辑。C需要一个特定值element_123。根据所使用的芯片,获得该值的方式有所不同:
对于芯片A,element_123是元素1和element8的组合。对于芯片b,element_123是element_a,element_b,element_y和element_z.
的组合 至关重要的是,使用element_123的program.c中的代码应在不同的项目中保持相同。唯一的变量是选择基础芯片。program.c
agent_t agent = {0};
if (agent_get_element_123(&agent) != true) {return;}
uint8_t data = agent.element_123 + some_data;
/*do other things...*/
/*agent.c*/
bool agent_get_element_123(agent_t* me)
{
chip_a_t chip_a = {0};
if ((chip_a_get_element1(&chip_a) != true)
|| (chip_a_get_element8(&chip_a) != true))
{
return false;
}
me->element_123 = chip_a.element1 + chip_a.element8;
return true;
}
在它站立的情况下,代理模块紧密耦合到chip_a模块,使其仅适用于项目A。要在项目B中使用芯片B,我需要一个单独的Agent.c。 我的问题是:有没有办法编写代理。C代码可以在不同的项目中无缝使用它(可能会使用芯片A或芯片B),而无需任何修改程序。C
additional信息:
在任何给定时间,硬件将始终仅支持一种类型的芯片。不可能同时在同一硬件上同时存在芯片A和芯片B。单个项目可能包含芯片A和芯片B的源代码,因为我们经常在项目之间复制整个项目文件夹。
有许多处理此类内容的方法,其中很多取决于您要做什么以及您的局限性是什么。
,例如,芯片之间的接口是相同的,因此Agent.C中的代码仅具有不同的函数名称? 然后,您只需写所有芯片即可具有相同的API并在您想要的任何一个中链接。
如果代码不同,是否可以引入一个高级接口,该接口在所有芯片上提供类似的API? 然后,您可以让每个芯片提供此接口,并将代理写入该接口。 您可以具有一系列功能指针,每个芯片都用它们的函数填充,然后Agent.c会选择该数组中的元素并调用函数。 您可以创建多个共享库,一个用于每个芯片,然后让Agent.c使用dlopen()选择正确的dlsym(),然后dlsym()获得函数的指针。您想要选择哪种芯片是
compile时间决策(使用预处理器选项选择),
link或chip_b的配置。 applose如果您想编译
chip_a,则
/* can be done in many ways, used this for simplicity */
#define CHIP_A TRUE
function()
{
/* common code */
#ifdef CHIP_A
/* CHIP_A related code */
#endif /* CHIP_A */
#ifdef CHIP_B
/* CHIP_B related code */
#endif /* CHIP_B */
/* common code */
}