Below is my header file , which declares the function set_params
#ifndef PID_H
#define PID_H
class PID
{
float _kp,_ki,_kd,_error,_previous_error,_dt;
public:
void set_params(float kp, float ki, float kd,float error,float previous_error,float dt);
};
#endif
The following is my pid.cpp, it contains function definition.
#include "PID.h"
void PID::set_params(float kp, float ki, float kd,float error,float previous_error,float dt)
{
_kp = kp;
_ki = ki;
_kd = kd;
_error = error;
_previous_error = previous_error;
_dt = dt;
}
The following is my main.cpp . I am using platformio in visual studio code
PID pid;
void setup() {
//
}
void loop()
{
pid.set_params(3.0,0.05,2.05,0.5,0.0,1.0);
}
I get the error as follows
It states that set_params is an undefined reference.
I compile it by clicking this button marked with red, in reality I do not know how to compile thej pid.cpp file separately. If there is any way please provide me a link.
Please tell me where I am mistaken.
Thanking you
CodePudding user response:
After you comment, even if including the cpp files is a workaround, please do not do that!
You have two acceptable ways.
define the method in the class itself in the include file
Some IDE by default create an include file containing only the method declarations and put the definitions in an implementation cpp file. But the standard allow the definition to be inside the class definition, it is commonly used for small methods or templates (*)
So your header could be:
#ifndef PID_H #define PID_H class PID { float _kp,_ki,_kd,_error,_previous_error,_dt; public: void set_params(float kp, float ki, float kd,float error,float previous_error,float dt) { _kp = kp; _ki = ki; _kd = kd; _error = error; _previous_error = previous_error; _dt = dt; } }; #endifadd the
pid.cppfile to the list of source files for your project.This part actually depends on your build tools. But your screenshot shows that you already compile
app.cppandmain.cpp. You just have to processpid.cppthe same way.
For templates, the recommended way is to put all the implementation in the include file. Not doing so requires to consistently explicitely instanciate the template for all its future usages, which is not an option in a general library.
