c - 在头文件中定义变量而不是 C 中的函数(非全局)

标签 c header struct

当我尝试比较两个不同的代码时,我在我的 .map 文件中看不到任何内存变化。 这里有可遵循的“良好做法”吗?我应该还是不应该将变量放在标题中? 请注意,我可以有多个 PIDUpdate() 函数,我已经有两个(如果有任何区别的话)。

头文件中没有变量的第一个例子 -> main.c

static int16_t PIDUpdate(int16_t target, int16_t feedback) // Valve
{
static float pTerm, iTerm, dTerm;
static float PID;
int16_t CurrentError;
static float LastError, SumError;
uint16_t tick;
static uint16_t elapsed;
float Kp = 0.1, Ki = 0.1, Kd = 0.1;

Kp = (float) pGain/10000.0;
Ki = (float) iGain/10000.0;
Kd = (float) dGain/10000.0;

....
if(elapsed = tick - timestamp, elapsed < TRACKING_PERIOD)
    goto leave;

timestamp = tick;

CurrentError = target - feedback;

pTerm = Kp * CurrentError;

// Calculate the Integral State with appropriate Limiting
....
iTerm = Ki * SumError;

dTerm = Kd * (LastError - CurrentError);

LastError = CurrentError;

PID = pTerm + iTerm + dTerm;

control = PID;
....
    leave:
return (control);
      }

另一个在标题中使用变量的例子 -> main.h

typedef struct PID
{
// PID parameters
uint16_t Kp; // pGain
uint16_t Ki; // iGain
uint16_t Kd; // dGain

// PID calculations
float pTerm;
float iTerm;
float dTerm;
float PID;

// Extra variabels
int16_t CurrentError;

// PID Time
uint16_t tick;

   }pid_object;

   typedef static struct staticPID
   {    
// Extra variabels
int16_t control;
float LastError;
float SumError;

// PID Time
uint16_t elapsed;
uint16_t timestamp;

    }StaticPid_object;

现在 main.c 代码与上面的 .h 文件放在一起

static int16_t PIDUpdate(int16_t target, int16_t feedback) // Valve
{
pid_object _PID_t;
StaticPid_object _StatPID_t;

_PID_t.Kp = (float) pGain/10000.0;
_PID_t.Ki = (float) iGain/10000.0;
_PID_t.Kd = (float) dGain/10000.0;

if(_StatPID_t.elapsed = _PID_t.tick - _StatPID_t.timestamp, _StatPID_t.elapsed < TRACKING_PERIOD)
    goto leave;

_StatPID_t.timestamp = _PID_t.tick;

_PID_t.CurrentError = target - feedback;

_PID_t.pTerm = _PID_t.Kp * _PID_t.CurrentError;

// Calculate the Integral State with appropriate Limiting
....

_PID_t.iTerm = _PID_t.Ki * _StatPID_t.SumError;

_PID_t.dTerm = _PID_t.Kd * (_StatPID_t.LastError - _PID_t.CurrentError);

_StatPID_t.LastError = _PID_t.CurrentError;

_PID_t.PID = _PID_t.pTerm + _PID_t.iTerm + _PID_t.dTerm;

_StatPID_t.control = 255-_PID_t.PID; // Make it work oposite to Heater

     leave:
return (_StatPID_t.control);
     }

最佳答案

你的代码在哪里并不重要——在 .h.c 中,但如果你在多个文件中包含定义静态变量的 header ,你每个文件都有不同的实例。重要的是这是否是您想要的。

关于c - 在头文件中定义变量而不是 C 中的函数(非全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8751270/

相关文章:

PHP header HTTP 1.0 与 1.1

c - typedef 在同一结构上使用两次

c - getsockopt api设计问题

c - 位集隶属函数

html - 将标题按钮居中而不使其成为静态/绝对

c++ - 如果我在头文件中实现一个类会怎样?

c++ - 在 C++ 中初始化 C 结构

c - C中结构中的多个灵活数组?

c++ - 识别 C 文件和包含的头文件之间依赖关系的工具/方法

c - 运行 Redis 的大量 TIME_WAIT 套接字连接