我正在从事一些项目,在这些项目中,我同时在客户端和供应商端编写代码。
假设在project_A中我选择chip_A,在project_B中我选择chip_B,chip_A和chip_B都提供类似的功能。
接下来,我将chip_A和chip_B分别封装到模块中。
chip_a.h
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);假设程序代码需要一个element_123 ( chip_A是element_1和element_8的组合,chip_B是element_a、element_b、element_y和element_z的组合),即使在不同的项目中,程序文本也总是相同的;项目之间的区别只是芯片的选择。
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 .c
/*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模块,而代理模块只对project_A可用;将代理模块绑定到chip_b仅适用于project_B。
是否有方法为不同的projcet编写相同的客户端文本(agent.c)?
FYI:
发布于 2021-03-05 15:08:47
处理这样的事情有很多种方法,这在很大程度上取决于你到底想要做什么,以及你的限制是什么。
例如,芯片之间的接口是否相同,因此agent.c中的代码是相同的,只是函数名不同?然后,您可以编写所有的芯片,以具有相同的API和链接在任何你想要的。
如果代码不同,是否有可能引入一个更高级的接口,在所有芯片之间提供类似的API?然后,您可以让每个芯片提供这个接口,并将代理程序写到该接口上。
您可以有一个函数指针数组,每个芯片都用它们的函数填充它,然后agent.c将选择该数组中的元素并调用该函数。
您可以创建多个共享库,每个芯片一个,然后让agent.c使用dlopen()选择正确的库,dlsym()获取函数的指针。
您想要选择哪个芯片用于编译时决策(使用预处理器选项来选择)、链接时决策(具有相同API的不同对象文件中的链接)还是运行时决策(在运行时选择不同的共享库)?
发布于 2021-03-05 07:53:11
您需要的是有条件编译,您需要在编译时为CHIP_A或CHIP_B启用配置。
假设如果要为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 */
}https://stackoverflow.com/questions/66488449
复制相似问题