3

我们有一个用于几个嵌入式系统的通用 C 库,它们都使用静态(即编译时)分配。

所以,这意味着我们通常有一些东西可以归结为这一点(如果我们不想更改公共源文件):

#define TMR_MAX 100
int actual_number_of_timers;
SoftTimer softTimers[TMR_MAX];

换句话说,为了避免 malloc'ing,实际上浪费了很多空间。

或者我们可以这样做,即为每个项目设置一组新的枚举:

enum TimerType
{
    TMR_KEYBOARD = 0,
    TMR_LCD,
    ...,
    TMR_MAX
};

SoftTimer softTimers[TMR_MAX];

这种另一种情况不会浪费空间,但这意味着每个项目都会更改(比如说)timer.h文件以定义自己的常量。顺便说一句,计时器示例只是原理的一个示例。

那么有没有一种更聪明的方法来获得像编译时“恰到好处的大小”分配这样的东西,它仍然允许我们拥有一个带有单独测试的通用“冻结”代码库?

4

3 回答 3

1

How flexible is your toolchain, in particular the link editor? With the GNU toolchain and ELF targets, you could have individual timer variables (instead of an array) and put them into a specific section:

SoftTimer softTimers __attribute__ ((section ("alloc_timers")));

GNU ld will synthesize special __start_alloc_timers and __stop_alloc_timers symbols which you could use to iterate over the timers. Of course, you would have to identify the timers by their variable names (or pointers) and could no longer use enum constants for that.

于 2017-07-21T14:26:48.453 回答
1

按照Sergey 的回答,将 etc. 的定义TMR_MAX从相关的头文件中移出,但不是在命令行上定义它们,您可以拥有一个configuration.h特定于每个项目的文件:

// Configuration settings for project XYZ

#define TMR_MAX (3)
#define WIDGET_COUNT (23)
...

然后,这将包含在所有其他标头之前的源文件中:

// Widget-timing module for project XYZ

#include "configuration.h"
#include "timer.h"
#include "widget.h"
...
于 2017-07-21T14:33:42.883 回答
1

TMR_MAX作为宏标志传递给您的编译器。例如对于 GCC,它将是:

#include <stdio.h>

int main ()
{
    printf ("%d\n", TMR_MAX);
}

gcc main.c -DTMR_MAX=42 && ./a.out42

于 2017-07-21T14:19:52.853 回答